using MySql.Data.MySqlClient;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;


namespace ZktecoAttendenceService
{
    class AttendanceMachineUserDAO
    {

        static bool result;
        public zkemkeeper.CZKEMClass axCZKEM1 = new zkemkeeper.CZKEMClass();
        List<string> responses;
        bool MachineOutput = true;

        public AttendanceMachineUserDAO() { }

        AttendanceMachine machine = new AttendanceMachine();

        public void Add(AttendanceMachineUser attendanceMachineUser, MySqlConnection connection)
        {
            string query = "REPLACE INTO `hrms`.`attendance_machine_user` (`machine_id`, `serial_number`, `employee_name`) VALUES (@MachineId, @SerialNumber, @EmployeeName)";

            MySqlCommand cmd = new MySqlCommand(query, connection);
            cmd.Parameters.AddWithValue("@machineId", attendanceMachineUser.MachineId);
            cmd.Parameters.AddWithValue("@SerialNumber", attendanceMachineUser.SerialNumber);
            cmd.Parameters.AddWithValue("@EmployeeName", attendanceMachineUser.EmployeeName);

            cmd.ExecuteNonQuery();

        }


        public List<AttendanceMachineUser> getAllEmployees(MySqlConnection connection)
        {
            List<AttendanceMachineUser> DBusers = null;
            string query = "select * from hrms.attendance_machine_user where is_deleted = 0";
            MySqlCommand cmd = new MySqlCommand(query, connection);
            MySqlDataReader reader = cmd.ExecuteReader();

            if (reader != null)
            {
                DBusers = getDBUsers(reader);
                reader.Close();
            }
            return DBusers;
        }


        public DataTable getAllEmployees_MachineWise(MySqlConnection connection, string MachineID)
        {
            DataTable DBusers = new DataTable();
            string query = "select * from hrms.attendance_machine_user a where a.machine_id = '" + MachineID + "' and a.is_deleted = 0 ";
            MySqlCommand cmd = new MySqlCommand(query, connection);
            MySqlDataAdapter AdtMysql = new MySqlDataAdapter();
            AdtMysql.SelectCommand = cmd;
            AdtMysql.Fill(DBusers);

            return DBusers;
        }

        private List<AttendanceMachineUser> getDBUsers(MySqlDataReader reader)
        {
            List<AttendanceMachineUser> DbUsers = new List<AttendanceMachineUser>();
            while (reader.Read())
            {
                DbUsers.Add(GetDbUsers(reader));
            }
            return DbUsers;
        }


        private AttendanceMachineUser GetDbUsers(MySqlDataReader reader)
        {
            return new AttendanceMachineUser(
                    reader.IsDBNull(0) ? "" : reader.GetString("machine_id"),
                    reader.IsDBNull(1) ? "" : reader.GetString("serial_number"),
                    reader.IsDBNull(2) ? "" : reader.GetString("employee_name"),
                    reader.IsDBNull(3) ? default(int) : reader.GetInt16("is_deletion_requested"),
                    reader.IsDBNull(4) ? default(int) : reader.GetInt16("is_deleted")
                );
        }
        string DTvalue;
        public List<string> saveMachineUsers(DataTable DBusersMachineWise, List<string> response, MySqlConnection mySqlConnection,string machineID)
        {

            List<string> responses = new List<string>();
            // Create a HashSet to store all values in the DataTable for faster lookup
            HashSet<string> dbValues = new HashSet<string>();
            foreach (DataRow row in DBusersMachineWise.Rows)
            {
                string dbValue = row["serial_number"].ToString();
                dbValues.Add(dbValue);
            }

            foreach (string value in response)
            {
                if (!dbValues.Contains(value))
                {
                    // Value not found in the DataTable
                    Console.WriteLine("Save in db" + value);

                    // You may want to add more logic here based on your requirements
                    AttendanceMachineUser addinDb = new AttendanceMachineUser(machineID, value, "", 0, 0);
                    Add(addinDb, mySqlConnection);
                    responses.Add(value + "--> Save in db");
                }
            }

            return responses;
        }
        //  bool Bconnect = false;
        public void DeleteFaceTemplate(zkemkeeper.CZKEMClass axCZKEM1, AttendanceMachine machine, int Emp_ID, List<string> responses)
        {
            //Bconnect = axCZKEM1.Connect_Net(machine.MachineIp, machine.PortNumber);
            //axCZKEM1.EnableDevice(Convert.ToInt32(machine.MachineId), false);//disable the device

            try
            {
              

                    axCZKEM1.SSR_DeleteEnrollData(Convert.ToInt32(machine.MachineId), Emp_ID.ToString(), 12);
                    Console.WriteLine(Emp_ID + " removed from " + machine.MachineId);
                    responses.Add(Emp_ID + " removed from " + machine.MachineId);
                    MachineOutput = true;

                    //axCZKEM1.EnableDevice(Convert.ToInt32(machine.MachineId), true);

                    //axCZKEM1.Disconnect();
             

            }

            catch (Exception ex)
            {

            }

        }



        public List<string> DeleteFromDbAndMachine(zkemkeeper.CZKEMClass cZKEM,List<string> objDetail_Final, AttendanceMachine machine, MySqlConnection connection)
        {

            List<string> responses = new List<string>();
            DataTable TableMachineUsers = new DataTable();

            TableMachineUsers = getAllEmployees_MachineWise(connection, machine.MachineId);
            DataColumn isProcessedColumn = TableMachineUsers.Columns.Add("IsProcessed", typeof(bool));
            foreach (DataRow row in TableMachineUsers.Rows)
            {
                // Set the value of the "IsProcessed" column to true for each row
                row["IsProcessed"] = false;
            }


            if (TableMachineUsers.Rows.Count > 0)
            {
                foreach (DataRow dr in TableMachineUsers.Rows)
                {
                    //string serial_no = "=" + '"' + dr["serial_number"].ToString() + '"' + ' ';
                    string serial_no = dr["serial_number"].ToString();
                    if (objDetail_Final.Contains(serial_no))
                    {
                        if (dr["is_deletion_requested"].ToString() == "1")
                        {
                            //removing face template 
                            DeleteFaceTemplate(cZKEM, machine, Convert.ToInt32(serial_no), responses);
                    
                            //Updating flag in db

                            if (MachineOutput == true)
                            {
                                UpdateFlag_InMachineUsers(machine.MachineId, serial_no, connection);
                                dr["IsProcessed"] = true;
                            }
                        }

                    }
                    else
                    {
                        if (dr["is_deleted"].ToString() == "0")
                        {
                            //UPDATE FLAG IN DATABASE
                            UpdateFlag_InMachineUsers(machine.MachineId, serial_no, connection);
                            responses.Add(serial_no + " marked deleted in db --> " + machine.MachineId);
                            Console.WriteLine(serial_no + " marked deleted in db --> " + machine.MachineId);
                        }
                    }
                }

                // Save Machine Users In Db
                responses.AddRange(saveMachineUsers(TableMachineUsers, objDetail_Final,connection, machine.MachineId));

            }
            else
            {
                for (int i = 0; i < objDetail_Final.Count; i++)
                {
                    string value = objDetail_Final[i].ToString();
                    AttendanceMachineUser temp = new AttendanceMachineUser(machine.MachineId, value, "", 0, 0);
                    Add(temp, connection);
                }

            }
            return responses;
        }


        public void UpdateTotalEmpInMachines(string machine_id, int total_users, MySqlConnection connection)
        {
    
            string query = "UPDATE `hrms`.`attendance_machine` SET `total_users` =" + total_users + "  WHERE `machine_id` = '" + machine_id + "'";
            MySqlCommand cmd = new MySqlCommand(query, connection);
            cmd.ExecuteNonQuery();
           
        }

        public void UpdateFlag_InMachineUsers(string machine_id, string serial_no, MySqlConnection connection)
        {
            string query = "UPDATE `hrms`.`attendance_machine_user` SET `is_deleted` = 1  WHERE `machine_id` = '" + machine_id + "' and serial_number = " + serial_no + "";
            MySqlCommand cmd = new MySqlCommand(query, connection);
            cmd.ExecuteNonQuery();
            
        }
    }
}
