using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;

namespace eDosStation
{
    public class Station
    {
        public int ID_Station { get; set; }
        public int ComPort { get; set; }
        public int Inst_CODE1 { get; set; }
        public int Inst_CODE2 { get; set; }
        public string Inst_Name1 { get; set; }
        public string Inst_Name2 { get; set; }
        public string TestCSN { get; set; }
        public string TestCode { get; set; }
        public string Reader { get; internal set; }
        public bool useTestButtons { get;  set; }
        public byte useBeep { get; set; }
        public bool checkUser { get; internal set; }

        public int EPDTimeOut { get; internal set; }
        public bool Changed = false;
        public int Error = 0;
        public string ErrorMessage;
        public StringBuilder insComments;
        public TextBlock tbComments;
        public DataInterface dataInterface;

        public System.Collections.Generic.Dictionary<byte, ushort> beepMk3Map;

        public ushort useBeepMK3()
        {
            if (beepMk3Map.ContainsKey(useBeep))
                return beepMk3Map[useBeep];
            else return beepMk3Map[0b00011010];
        }


        public Station(DataInterface mDataInterface, string Station)
        {
            dataInterface = mDataInterface;
            Error = 0;
            ErrorMessage = string.Empty;
            ComPort = 0;
            Inst_CODE1 = 1;
            Inst_CODE2 = 11;
            Inst_Name1 = "BR1";
            Inst_Name2 = "Venus";
            TestCSN = System.Configuration.ConfigurationManager.AppSettings["TestCSN"];
            TestCode = System.Configuration.ConfigurationManager.AppSettings["TestCode"];
            insComments = new StringBuilder();
            tbComments = new TextBlock();
            tbComments.FontSize = 20;
            tbComments.HorizontalAlignment = System.Windows.HorizontalAlignment.Stretch;
            tbComments.TextAlignment = System.Windows.TextAlignment.Center;
            EPDTimeOut = 10000; //ms

            beepMk3Map = new Dictionary<byte, ushort>();
            beepMk3Map.Add(0b00010111, 0b1001110011100001);
            beepMk3Map.Add(0b00011111, 0b1001110011000001);
            beepMk3Map.Add(0b00010110, 0b1001110010100001);
            beepMk3Map.Add(0b00011110, 0b1001110010000001);
            beepMk3Map.Add(0b00011010, 0b1001110000000000);

            var co = dataInterface.getCon(true);  // No dispose
            {
                using (var cmd = new SqlCommand("StationSettingsSelect", co))
                {
                    cmd.CommandType = System.Data.CommandType.StoredProcedure;
                    try
                    {
                        var rs = cmd.ExecuteReader(System.Data.CommandBehavior.SingleRow);
                        if (rs.HasRows && rs.Read())
                        {
                            object[] Values = new object[rs.FieldCount];
                            int rv = rs.GetValues(Values);
                            ID_Station = (int)Values[rs.GetOrdinal("ID_Station")];
                            ComPort = (int)Values[rs.GetOrdinal("ComPort")];
                            int c = rs.GetOrdinal("Inst_CODE1");
                            if (rs.IsDBNull(c)) Inst_CODE1 = 0; else Inst_CODE1 = (int)Values[c];
                            c = rs.GetOrdinal("Inst_CODE2");
                            if (rs.IsDBNull(c)) Inst_CODE2 = 0; else Inst_CODE2 = (int)Values[c];
                            c = rs.GetOrdinal("Inst_Name1");
                            if (rs.IsDBNull(c)) Inst_Name1=string.Empty; else Inst_Name1 = Values[c].ToString();
                            c = rs.GetOrdinal("Inst_Name2");
                            if (rs.IsDBNull(c)) Inst_Name2 = string.Empty; else Inst_Name2 = Values[c].ToString();
                            c = rs.GetOrdinal("TestCSN");
                            if (rs.IsDBNull(c)) TestCSN = string.Empty; else TestCSN = Values[c].ToString();
                            c = rs.GetOrdinal("Reader");
                            if (rs.IsDBNull(c)) Reader = string.Empty; else Reader = Values[c].ToString();

                            try
                            {
                                c = rs.GetOrdinal("useTestButtons");
                                if (rs.IsDBNull(c)) useTestButtons = false; else useTestButtons = (bool)Values[c];
                            }
                            catch { useTestButtons = false; }
                            try
                            {
                                c = rs.GetOrdinal("useBeep");
                                if (rs.IsDBNull(c)) useBeep = 0b00010110; else useBeep = (byte)Values[c];
                            }
                            catch { useBeep = 0b00010110; }

                            try
                            {
                                c = rs.GetOrdinal("checkUser");
                                if (rs.IsDBNull(c)) checkUser = false; else checkUser= (bool)Values[c];
                            }
                            catch { checkUser=false; }
                            try
                            {
                                c = rs.GetOrdinal("EPDTimeout");
                                if (rs.IsDBNull(c)) EPDTimeOut = 10000; else EPDTimeOut= (int)Values[c];
                            }
                            catch { EPDTimeOut= 10000; }
                        }
                        else
                        {
                            ID_Station = 0;
                            ComPort = 0;
                            Inst_CODE1 = 1;
                            Inst_CODE2 = 11;
                            Inst_Name1 = "BR1"; Inst_Name2 = "Venus";
                            TestCSN = System.Configuration.ConfigurationManager.AppSettings["TestCSN"];
                            TestCode = System.Configuration.ConfigurationManager.AppSettings["TestCode"];
                            Changed = true;
                            Reader = System.Configuration.ConfigurationManager.AppSettings["Reader"];
                            checkUser = false;
                            EPDTimeOut = 10000;
                        }
                        rs.Close();
                    }
                    catch (System.Exception ex)
                    {
                        Error = 1;
                        ErrorMessage = ex.Message;
                    }
                }

                dataInterface.SetStation(ID_Station);
                dataInterface.SetCheckUser(checkUser);

                if (Error == 0) using (var cmd2 = new SqlCommand("GetInstallationsComments", co))
                    {
                        cmd2.CommandType = System.Data.CommandType.StoredProcedure;
                        cmd2.Parameters.AddWithValue("@Inst_CODE1", Inst_CODE1);
                        if (Inst_CODE2 > 0) cmd2.Parameters.AddWithValue("@Inst_CODE2", Inst_CODE2);
                        try
                        {
                            var rs = cmd2.ExecuteReader(System.Data.CommandBehavior.SingleResult);
                            string curins = string.Empty, thisins = string.Empty, thiscomment = string.Empty;
                            if (rs.HasRows)
                                while (rs.Read())
                                {
                                    thisins = rs.GetString(2);
                                    thiscomment = rs.GetString(3).Replace("\\n", "\n");
                                    if (curins.CompareTo(thisins) != 0)
                                    {
                                        if (curins != string.Empty) tbComments.Inlines.Add(new LineBreak());
                                        tbComments.Inlines.Add(new Bold(new Run($"Installation {thisins}:\n") { FontSize = 25 }));
                                        insComments.AppendLine($"Installation {thisins}");
                                        curins = thisins;
                                    }
                                    tbComments.Inlines.Add(new Run(thiscomment));
                                }
                            rs.Close();
                        }
                        catch (System.Exception ex)
                        {
                            Error = 2;
                            ErrorMessage = ex.Message;
                        }
                    }
                co?.Close();
            }
        }


        private void UpdateToDb(SqlConnection co, SqlCommand cmd)
        {
            cmd.Connection = co;
            cmd.ExecuteNonQuery();
        }
        public void Update()
        {

            SqlConnection co=null;
            using (var cmd = new SqlCommand("StationSettingsUpdate"))
            {
                cmd.CommandType = System.Data.CommandType.StoredProcedure;
                cmd.Parameters.AddWithValue("ComPort", ComPort);

                if (!string.IsNullOrEmpty(Inst_Name1) && Inst_CODE1 > 0)
                {
                    cmd.Parameters.AddWithValue("Inst_CODE1", Inst_CODE1);
                    cmd.Parameters.AddWithValue("Inst_Name1", Inst_Name1);
                }

                if (!string.IsNullOrEmpty(Inst_Name2) && Inst_CODE2 > 0)
                {
                    cmd.Parameters.AddWithValue("Inst_CODE2", Inst_CODE2);
                    cmd.Parameters.AddWithValue("Inst_Name2", Inst_Name2);
                }
                //if (!string.IsNullOrEmpty(TestCSN))
                //    cmd.Parameters.AddWithValue("TestCSN", TestCSN);

                if (!string.IsNullOrEmpty(Reader))
                    cmd.Parameters.AddWithValue("Reader", Reader);

                cmd.Parameters.AddWithValue("checkUser", checkUser);
                cmd.Parameters.AddWithValue("useBeep", useBeep);
                cmd.Parameters.AddWithValue("EPDTimeout", EPDTimeOut);

                try
                {
                    co = dataInterface.getCon(true);
                    UpdateToDb(co, cmd);
                    co.Close();
                    co = dataInterface.getConCentral(true);
                    UpdateToDb(co, cmd);
                }
                catch (System.Exception ex)
                {
                    Error = 1;
                    ErrorMessage = ex.Message;
                }
                co?.Close();
            }

        }

       
    }
}

