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

namespace UtopiaAttService
{
    class SaveTemplate
    {
        public void CheckInDb(MySqlConnection connection, string employeeId , string responseMachine)
        {
            // Check if the serial number already exists in the database
            string checkQuery = "SELECT COUNT(*) FROM attendance_machine_face_templates WHERE serial_no = @SerialNumber";
            using (MySqlCommand checkCommand = new MySqlCommand(checkQuery, connection))
            {
                checkCommand.Parameters.AddWithValue("@SerialNumber", employeeId);
                object result = checkCommand.ExecuteScalar();

                if (result != null && result != DBNull.Value)
                {
                    int count;
                    if (int.TryParse(result.ToString(), out count))
                    {
                        if (count == 0)
                        {
                            SaveInDatabase(connection, employeeId, responseMachine);
                        }
                        else
                        {
                            Console.WriteLine("Serial number already exists in the database.");
                        }
                    }

                }
            }
        }
        public void SaveInDatabase(MySqlConnection connection, string employeeId, string responseMachine)
        {
            // Serial number doesn't exist, so add it to the database
            string insertQuery = "INSERT INTO attendance_machine_face_templates (serial_no,template,created_date) VALUES (@SerialNumber,@FaceTemplate,@created_date)";
            using (MySqlCommand insertCommand = new MySqlCommand(insertQuery, connection))
            {
                insertCommand.Parameters.AddWithValue("@SerialNumber", employeeId);
                insertCommand.Parameters.AddWithValue("@FaceTemplate", responseMachine);
                insertCommand.Parameters.AddWithValue("@created_date", System.DateTime.Now);
                int rowsAffected = insertCommand.ExecuteNonQuery();

                if (rowsAffected > 0)
                {

                    Console.WriteLine("Face template added to the database.");
                    //GetBlobValue(employeeId);
                    responseMachine = "";
                    employeeId = "";


                }
                else
                {
                    Console.WriteLine("Failed to add face template to the database.");
                }
            }
        }
    }
}
