using MySql.Data.MySqlClient;
using Org.BouncyCastle.Crypto.IO;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ZktecoAttendenceService
{
    internal class SaveTemplateDb
    {


        string empID;
        string template;
        int length = 0;
        long empExist; long templateExist;
        public void InsertFaceIntoDb(AttendanceMachine attendanceMachine, MySqlConnection connection, zkemkeeper.CZKEMClass axCZKEM1)
        {
            try
            {
                string sName;
                string sPassword;
                int iPrivilege;
                bool bEnabled;
                int machineNo = Convert.ToInt32(attendanceMachine.MachineId);

                // Create a list to store emp ID and template
               
                List<(string, string,long,long)> empTemplateList = new List<(string, string,long,long)>();
                // Get all emp 
               

                while (axCZKEM1.SSR_GetAllUserInfo(machineNo, out empID, out sName, out sPassword, out iPrivilege, out bEnabled))
                {                 
                    {

                        ( empExist,  templateExist) = CheckEmpInDb(empID, connection);

                       
                        if (templateExist == 0 )
                        {
                          
                            if (axCZKEM1.GetUserFaceStr(machineNo, empID, 50, ref template, ref length))
                            {
                                Console.WriteLine("User ID: " + empID + " Name: " + sName + " Template: " + template + " Length: " + length);
                                // Store emp ID and template in the list
                                empTemplateList.Add((empID, template,empExist, templateExist));

                            }
                        }
                    }
                }


                //axCZKEM1.EnableDevice(machineNo, true);
                //axCZKEM1.Disconnect();


                SaveInDb(empTemplateList, connection);
            }
            catch (Exception ex)
            {
                // Handle exception
            }
        }
        //save template to db with emp id and template parameter   
        public void SaveInDb(List<(string, string, long, long)> empTemplateList, MySqlConnection connection)
        {
           
            foreach (var item in empTemplateList)
            {
                
                long empExist = item.Item3;
                long empTemplateExist = item.Item4;
                if (empExist == 0 && empTemplateExist == 0)
                {
                    string insertQuery = "INSERT INTO attendance_machine_face_templates (serial_no, template_zkteco, created_date) VALUES (@emp_id, @template, @created_date)";
                   
                    MySqlCommand command = new MySqlCommand(insertQuery, connection);

                    command.Parameters.AddWithValue("@emp_id", item.Item1);
                    command.Parameters.AddWithValue("@template", item.Item2);
                    command.Parameters.AddWithValue("@created_date", DateTime.Now);
                    command.ExecuteNonQuery();
                    command.Parameters.Clear();
                    Console.WriteLine("Emp id " + item.Item1 + " Inserted");
                }
               if (empExist == 1 && empTemplateExist == 0)
                {
                    string updateQuery = "UPDATE attendance_machine_face_templates set template_zkteco = @template where serial_no = @emp_id and is_active = 1";
                    MySqlCommand command = new MySqlCommand(updateQuery, connection);

                    command.Parameters.AddWithValue("@emp_id", item.Item1);
                    command.Parameters.AddWithValue("@template", item.Item2);
                    command.Parameters.AddWithValue("@created_date", DateTime.Now);
                    command.ExecuteNonQuery();
                    command.Parameters.Clear();
                    Console.WriteLine("Employee already exist");
                }
            }
           
        }

        public (long EmpExist, long TemplateExist) CheckEmpInDb(string empId, MySqlConnection connection)
        {
            string query = @"
        SELECT 
            COUNT(*) AS EmpExist,
            CASE 
                WHEN COUNT(*) = 0 THEN 0  -- If no employee exists, set TemplateExist to 0
                ELSE SUM(CASE WHEN template_zkteco IS NULL THEN 0 ELSE 1 END) 
            END AS TemplateExist
        FROM attendance_machine_face_templates
        WHERE is_active = 1 AND serial_no = @emp_id";

            using (MySqlCommand command = new MySqlCommand(query, connection))
            {
                command.Parameters.AddWithValue("@emp_id", empId);

                if (connection.State != ConnectionState.Open)
                {
                    connection.Open();
                }

                using (MySqlDataReader reader = command.ExecuteReader())
                {
                    if (reader.Read())
                    {
                        long empExist = reader.GetInt64(0);  // First column (EmpExist)
                        long templateExist = reader.GetInt64(1); // Second column (TemplateExist)

                        return (empExist, templateExist);
                    }
                }
            }

            //close connection 
            connection.Close();
            return (0, 0); // Return (0, 0) if no data is found
        }
    }

}
