//commentaar
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Maser.Feanor.Model;
using System.Net;
using Maser.Feanor.Biz;
using System.Globalization;
using System.Net.NetworkInformation;




namespace Maser.Feanor.Server
{
    public class RaspberryPI : Server
    {
        public const ServerType SERVERTYPE = ServerType.RaspberryPI;
       
        public RaspberryPI(Chamber Chamber) : base(Chamber)
        {
            _chamber = Chamber;
        }


        // Return a list of standard defined sensors for RaspberryPI
        public override List<Sensor> StandardSensors()
        {   
            // Format: int PK, int ID, int chamberPK, String Description, SensorType, Enabled: true/false, ApplyCalibration: true/false

            List<Sensor> sensors = new List<Sensor>();
            sensors.Add(new Sensor(-1, 0, _chamber.PK, "Air temperature", SensorType.Pt100, true, false)); // dry bulb
            sensors.Add(new Sensor(-1, 1, _chamber.PK, "Water temperature", SensorType.Pt100, true, false)); // wet bulb
           
            sensors.Add(new Sensor(-1, 2, _chamber.PK, String.Format("Voltage Ch01"), SensorType.Voltage, true, false));
            sensors.Add(new Sensor(-1, 3, _chamber.PK, String.Format("Voltage Ch02"), SensorType.Voltage, true, false));
            sensors.Add(new Sensor(-1, 4, _chamber.PK, String.Format("Voltage Ch03"), SensorType.Voltage, true, false));
            sensors.Add(new Sensor(-1, 5, _chamber.PK, String.Format("Voltage Ch04"), SensorType.Voltage, true, false));
            sensors.Add(new Sensor(-1, 6, _chamber.PK, String.Format("Voltage Ch05"), SensorType.Voltage, true, false));
            sensors.Add(new Sensor(-1, 7, _chamber.PK, String.Format("Voltage Ch06"), SensorType.Voltage, true, false));
            sensors.Add(new Sensor(-1, 8, _chamber.PK, String.Format("Voltage Ch07"), SensorType.Voltage, true, false));
            sensors.Add(new Sensor(-1, 9, _chamber.PK, String.Format("Voltage Ch08"), SensorType.Voltage, true, false));
            sensors.Add(new Sensor(-1, 10, _chamber.PK, String.Format("Voltage Ch09"), SensorType.Voltage, true, false));
            sensors.Add(new Sensor(-1, 11, _chamber.PK, String.Format("Voltage Ch10"), SensorType.Voltage, true, false));
            sensors.Add(new Sensor(-1, 12, _chamber.PK, String.Format("Voltage Ch11"), SensorType.Voltage, true, false));
            sensors.Add(new Sensor(-1, 13, _chamber.PK, String.Format("Voltage Ch12"), SensorType.Voltage, true, false));
            sensors.Add(new Sensor(-1, 14, _chamber.PK, String.Format("Voltage Ch13"), SensorType.Voltage, true, false));
            sensors.Add(new Sensor(-1, 15, _chamber.PK, String.Format("Voltage Ch14"), SensorType.Voltage, true, false));
            sensors.Add(new Sensor(-1, 16, _chamber.PK, String.Format("Voltage Ch15"), SensorType.Voltage, true, false));
            sensors.Add(new Sensor(-1, 17, _chamber.PK, String.Format("Voltage Ch16"), SensorType.Voltage, true, false));

            sensors.Add(new Sensor(-1, 18, _chamber.PK, "RH psychrometer", SensorType.PsychrometerRH, true, false));
            sensors.Add(new Sensor(-1, 19, _chamber.PK, "RH pressurecooker", SensorType.PressurecookerRH, true, false));
            
            return sensors;
        }


        public override bool Read()
        {
            _Results = new List<Result>();

            string url = URL + "ContentToClient";            
            string data;
            //Console.WriteLine(url);
                       
            try
            {
                using (WebClient client = new WebClient())
                {
                    data = client.DownloadString(url);
                   
                    String[] objects = data.Split(';');
                    foreach (String obj in objects)
                    {
                        try
                        {
                            // Create Results from data-string
                            if (obj.Trim().StartsWith("<D>") && obj.Trim().EndsWith("</D>"))
                            {
                                string s = obj.Replace("<D>", "").Replace("</D>", "").Trim();
                                string[] vars = s.Split(',');
                                int ID = int.Parse(vars[0]);
                                DateTime dt = Time.UnixToDatetime(int.Parse(vars[1]));
                                float fValue = float.Parse(vars[2], CultureInfo.InvariantCulture);
                                int calibrationPK = int.Parse(vars[3]);
                                Int32 sensorPK = _Sensors.Find(delegate (Sensor sensor) { return (sensor.ID == ID); }).PK;

                                /*
                                if(ID == 0 || ID == 1) // temp
                                {
                                    Console.Write(ID.ToString());
                                    Console.Write("   ");
                                    Console.Write(fValue.ToString());
                                    Console.Write("   ");

                                    if(fValue < -500.0)
                                    {
                                        Console.WriteLine("Temperature not store in DB");
                                        // hier temp niet in DB opslaan
                                    }
                                    else
                                    {
                                        Console.WriteLine("Temperature store in DB");
                                        // hier temp wel in DB opslaan
                                    }
                                    
                                }
                                if(ID > 1 && ID < 18) // volt
                                {
                                    float VoltThreshold = 0.1f;

                                    Console.Write(ID.ToString());
                                    Console.Write("   ");
                                    Console.Write(fValue.ToString());
                                    Console.Write("   ");

                                    if(fValue > VoltThreshold || fValue < (-1.0*VoltThreshold ))
                                    {
                                        Console.WriteLine("VOLT store in DB");
                                        // hier voltage opslaan in DB
                                    }
                                    else
                                    {
                                        Console.WriteLine("VOLT not store in DB");
                                        // hier niets doen
                                    }
                                }
                                */                               

                                _Results.Add(new Result(-1, sensorPK, fValue, dt, calibrationPK));
                            }                            
                        }
                        catch
                        {
                            
                            // Continue with next object, ignoring exception
                        }

                    }
                }
            }
            catch
            {
                //Console.WriteLine("ERROR during data extraction");
                return false;
            }
            //Console.WriteLine("Succesfull data extraction");
            return true;
        }


        public bool ReadStartup()
        {
            DateTime zero = Time.UnixToDatetime(0);
            // return zero;      
            return false;
        }


        public override bool WriteDatetime(DateTime dt)
        {
            // Format: <time>,[unix timestamp],</time>

            string http = "<time>,";
            http += string.Format("{0},", Time.DatetimeToUnix(dt));
            http += "</time>";
            return HTTP_POST(http);
        }


        public override Boolean WriteInterval(Int32 Interval)
        {
            // Format: <interval>,[interval],</interval>
            string http = "<interval>,";
            http += string.Format("{0},", Interval);
            http += "</interval>";
            return HTTP_POST(http);
        }


        public override bool WriteSensors()
        {
            bool result = true;
            foreach (Sensor sensor in _Sensors)
            {
                Calibration cal = _Calibrations.Find(delegate (Calibration c) { return (c.SensorPK == sensor.PK); });
                if (cal == null)
                    cal = new Calibration(-1, sensor.PK, DateTime.Now, DateTime.Now, DateTime.Now, new double[2] { 0, 1 }, 0, new double[4] { 0, 0, 1, 1 });

                if (!ModifySensor(sensor, cal))
                    result = false;
            }
            return result;
        }


        public override bool ModifySensor(Sensor sensor, Calibration calibration)
        {
            // Format: <sensor>,ID,[Enabled:1/0],[ApplyCalibration:1/0],Description,CalibrationPK,c0,c1,...cn
            string sensorHTTP = "";
            sensorHTTP += "<sensor>,";
            sensorHTTP += sensor.ID.ToString() + ",";
            sensorHTTP += (sensor.Enabled) ? "1," : "0,";
            sensorHTTP += (sensor.ApplyCalibration) ? "1," : "0,";
            sensorHTTP += sensor.Description + ",";
            sensorHTTP += calibration.PK.ToString() + ",";
            sensorHTTP += String.Join(",", calibration.Coefficients);
            sensorHTTP += ",</sensor>"; // <-- de komma is later toegevoegd. zonder komma wordt c[3] niet herkend door het Python script van de RPI
            return HTTP_POST(sensorHTTP);
        }


        private bool HTTP_POST(string http)
        {
            /*
            var reqparm = new System.Collections.Specialized.NameValueCollection();
            reqparm.Add("param1", "<any> kinds & of = ? strings");
            reqparm.Add("param2", "escaping is already handled");
            byte[] responsebytes = client.UploadValues("http://localhost", "POST", reqparm);
            string responsebody = Encoding.UTF8.GetString(responsebytes);
            */
            try
            {
                using (WebClient wc = new WebClient())
                {
                    wc.Headers[HttpRequestHeader.ContentType] = "application/x-www-form-urlencoded";
                    string HtmlResult = wc.UploadString(URL, http);
                    if (HtmlResult != "OK")
                        return false;
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
            return true;
        }
    }




}
