using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace RegisterBAdge
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public static OkReadBadge.Badging a;
        System.Threading.Thread t;
        bool nextCSN = false;
        bool nextSite = false;
        bool nextCode = false;
        bool nextFinish = false;
        string csn, site, code;
        System.Data.SqlClient.SqlCommand UpdPers;

        public MainWindow()
        {
            InitializeComponent();
        }

        void CheckBadge()
        {
            using (var t = new System.Data.DataTable()) {
                using (var co = new System.Data.SqlClient.SqlConnection(Properties.Settings.Default.idpbwConnection))
                {
                using (var co2 = new System.Data.SqlClient.SqlConnection(Properties.Settings.Default.RemsConnection))
                {
                        using (var cm = new System.Data.SqlClient.SqlCommand("rems.GetPerson", co))
                        {
                            cm.CommandType = System.Data.CommandType.StoredProcedure;
                            cm.Parameters.AddWithValue("CSN", CSN.Text);
                            cm.Parameters.AddWithValue("Badge", Code.Text);
                            co.Open();
                            var rs = cm.ExecuteReader(System.Data.CommandBehavior.SingleRow | System.Data.CommandBehavior.CloseConnection);
                            t.Load(rs);
                            co.Close();
                            if (t.Rows.Count > 0)
                            {
                                co2.Open();
                                DataRow r = t.Rows[0];

                                PersID.Text = r["persID"].ToString();
                                Name.Text = r["LastName"].ToString();
                                FirstName.Text = (string)r["NickName"];

                                UpdPers.Parameters["persID"].Value = (int)r["persID"];
                                UpdPers.Parameters["TYPE"].Value = (string)r["TYPE"];
                                UpdPers.Parameters["CSN"].Value = (string)r["CSN"];
                                UpdPers.Parameters["Badge"].Value = (string)r["Badge"];
                                UpdPers.Parameters["firstname"].Value = (string)r["firstname"];
                                UpdPers.Parameters["LastName"].Value = (string)r["LastName"];
                                UpdPers.Parameters["NickName"].Value = (string)r["NickName"];
                                UpdPers.Parameters["birthDate"].Value = (DateTime)r["birthDate"];
                                //UpdPers.Parameters["conCode"].Value = (string)r["conCode"];
                                UpdPers.Parameters["AccessAllow"].Value = (Boolean)r["AccessAllow"];
                                UpdPers.Parameters["Language"].Value = (string)r["Language"];
                                UpdPers.Parameters["VisitIdLocked"].Value = DBNull.Value;
                                UpdPers.Parameters["Deleted"].Value = (Boolean)r["Deleted"];
                                UpdPers.Connection = co2;
                                UpdPers.ExecuteNonQuery();
                                co2.Close();
                            }
                        }
                    }
                }
            }
            //_User = new User(CSN.Text, Code.Text);
            //if (_User.Error == 0)
            //    AskTask();
            //else
            //{
            //    MessageBox.Show(_User.ErrorMessage);
            //    Close();
            //}
        }

        public void showBadge()
        {
            CSN.Text = csn;
            Site.Text = site;
            Code.Text = code;

            Dispatcher.Invoke(CheckBadge);
        }

        bool Msg(int err)
        {
            //decodeert verschillenden USB messages. (callback )
            if (err == 0)
            {
                if (a.clr.Result.StartsWith("csn:", StringComparison.InvariantCultureIgnoreCase) && a.clr.Result.EndsWith(";"))
                {  //GEn 2
                    csn = string.Empty;
                    foreach (string ar in a.clr.Result.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries))
                    {
                        if (ar.StartsWith("csn:")) csn = ar.Substring(4);
                        if (ar.StartsWith("site:")) site = ar.Substring(5);
                        if (ar.StartsWith("code:")) code = ar.Substring(5);
                    }
                    this.Dispatcher.Invoke(new Action(() => showBadge()));
                }
                else
                {
                    if (a.clr.Result.Equals(";"))
                    {
                        if (nextSite) site = string.Empty;
                        if (nextCode) code = string.Empty;
                        if (nextFinish || nextCode)
                        {
                            this.Dispatcher.Invoke(new Action(() => showBadge()));
                        }
                        nextCSN = nextSite = nextCode = nextFinish = false;
                    }
                    else if (nextCSN) { csn = a.clr.Result; nextCSN = nextFinish = false; }
                    else if (nextSite) { site = a.clr.Result; nextSite = false; }
                    else if (nextCode) { code = a.clr.Result; nextCode = false; nextFinish = true; }
                    else if (a.clr.Result.Equals("csn:")) { nextCSN = true; nextCode = nextSite = false; }
                    else if (a.clr.Result.Equals("site:")) { nextSite = true; nextCSN = nextCode = false; }
                    else if (a.clr.Result.Equals("code:")) { nextCode = true; nextCSN = nextSite = false; }
                    else System.Diagnostics.Debug.WriteLine(a.clr.Result);
                }
            }
            else
                System.Diagnostics.Debug.WriteLine($"Error {err}");
            return false;
        }

        private void Starter()
        {
            try
            {
                a = new OkReadBadge.Badging(Msg);
                a.Start();
            }
            catch (System.Exception ex)
            {
                MessageBox.Show($"Badgereader error {ex.Message}", "Error", MessageBoxButton.OK, MessageBoxImage.Exclamation);
            }
        }

        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            UpdPers = new System.Data.SqlClient.SqlCommand("UpdatePerson");
            UpdPers.CommandType = System.Data.CommandType.StoredProcedure;
            UpdPers.Parameters.Add(new System.Data.SqlClient.SqlParameter("RETURN_VALUE", System.Data.SqlDbType.Int, 0, System.Data.ParameterDirection.ReturnValue, false, 0, 0, null, System.Data.DataRowVersion.Current, DBNull.Value));
            UpdPers.Parameters.Add(new System.Data.SqlClient.SqlParameter("persID", System.Data.SqlDbType.Int, 0, System.Data.ParameterDirection.Input, false, 0, 0, null, System.Data.DataRowVersion.Current, DBNull.Value));
            UpdPers.Parameters.Add(new System.Data.SqlClient.SqlParameter("TYPE", System.Data.SqlDbType.Char, 1, System.Data.ParameterDirection.Input, false, 0, 0, null, System.Data.DataRowVersion.Current, DBNull.Value));
            UpdPers.Parameters.Add(new System.Data.SqlClient.SqlParameter("CSN", System.Data.SqlDbType.VarChar, 50, System.Data.ParameterDirection.Input, false, 0, 0, null, System.Data.DataRowVersion.Current, DBNull.Value));
            UpdPers.Parameters.Add(new System.Data.SqlClient.SqlParameter("Badge", System.Data.SqlDbType.VarChar, 20, System.Data.ParameterDirection.Input, false, 0, 0, null, System.Data.DataRowVersion.Current, DBNull.Value));
            UpdPers.Parameters.Add(new System.Data.SqlClient.SqlParameter("firstname", System.Data.SqlDbType.VarChar, 30, System.Data.ParameterDirection.Input, false, 0, 0, null, System.Data.DataRowVersion.Current, DBNull.Value));
            UpdPers.Parameters.Add(new System.Data.SqlClient.SqlParameter("LastName", System.Data.SqlDbType.VarChar, 30, System.Data.ParameterDirection.Input, false, 0, 0, null, System.Data.DataRowVersion.Current, DBNull.Value));
            UpdPers.Parameters.Add(new System.Data.SqlClient.SqlParameter("NickName", System.Data.SqlDbType.VarChar, 30, System.Data.ParameterDirection.Input, false, 0, 0, null, System.Data.DataRowVersion.Current, DBNull.Value));
            UpdPers.Parameters.Add(new System.Data.SqlClient.SqlParameter("birthDate", System.Data.SqlDbType.Date, 0, System.Data.ParameterDirection.Input, false, 0, 0, null, System.Data.DataRowVersion.Current, DBNull.Value));
            //UpdPers.Parameters.Add(new System.Data.SqlClient.SqlParameter("conCode", System.Data.SqlDbType.VarChar, 4, System.Data.ParameterDirection.Input, false, 0, 0, null, System.Data.DataRowVersion.Current, DBNull.Value));
            UpdPers.Parameters.Add(new System.Data.SqlClient.SqlParameter("AccessAllow", System.Data.SqlDbType.Bit, 0, System.Data.ParameterDirection.Input, false, 0, 0, null, System.Data.DataRowVersion.Current, DBNull.Value));
            UpdPers.Parameters.Add(new System.Data.SqlClient.SqlParameter("Language", System.Data.SqlDbType.Char, 1, System.Data.ParameterDirection.Input, false, 0, 0, null, System.Data.DataRowVersion.Current, DBNull.Value));
            UpdPers.Parameters.Add(new System.Data.SqlClient.SqlParameter("VisitIdLocked", System.Data.SqlDbType.Int, 0, System.Data.ParameterDirection.Input, false, 0, 0, null, System.Data.DataRowVersion.Current, DBNull.Value));
            UpdPers.Parameters.Add(new System.Data.SqlClient.SqlParameter("Deleted", System.Data.SqlDbType.Bit, 0, System.Data.ParameterDirection.Input, false, 0, 0, null, System.Data.DataRowVersion.Current, DBNull.Value));


            t = new System.Threading.Thread(() => Starter());
            t.Start();
        }

       
    }
}
