using Microsoft.EntityFrameworkCore;
using BMA.EHR.Recurit.Exam.Service.Data;
using System.Data;
using System.Globalization;

namespace BMA.EHR.Recurit.Exam.Service.Services
{
    public class DisableService
    {
        private readonly ApplicationDbContext _context;
        private readonly IConfiguration _configuration;
        private readonly IWebHostEnvironment _webHostEnvironment;

        public DisableService(ApplicationDbContext context,
                            IConfiguration configuration,
                            IWebHostEnvironment webHostEnvironment)
        {
            _context = context;
            _configuration = configuration;
            _webHostEnvironment = webHostEnvironment;
        }

        public int GetExamCount(string citizenId)
        {
            try
            {
                var count = _context.Candidates.AsQueryable()
                                    .Where(x => x.CitizenId == citizenId)
                                    .Count();

                return count;
            }
            catch
            {
                throw;
            }
        }

        public async Task<string> GetExamAttributeAsync(Guid period, Guid exam)
        {
            try
            {
                var payment = await _context.DisablePayments.AsQueryable()
                                        .Include(x => x.Disable)
                                        .ThenInclude(x => x.PeriodExam)
                                        .Where(x => x.Disable.Id == exam)
                                        .Where(x => x.Disable.PeriodExam.Id == period)
                                        .FirstOrDefaultAsync();

                return payment != null ? "มีคุณสมบัติ" : "ไม่มีคุณสมบัติ";
            }
            catch
            {
                throw;
            }
        }

        public bool CheckValidCertificate(DateTime certDate, int nextYear = 5)
        {
            var valid = true;
            if (DateTime.Now.Date > certDate.Date.AddYears(nextYear))
                valid = false;

            return valid;
        }

        public DateTime? CheckDateTime(string Date, string Formate)
        {
            // ตอนนี้ทำไว้ให้รองรับแค่ "dd/MM/yyyy", "yyyy-MM-dd"
            Date = Date.Trim();

            if (string.IsNullOrWhiteSpace(Date))
                return null;

            // จะเข้าเฉพาะกรณีที่ string เป็นตัวเลข เช่น "35635", "44561.5"
            if (double.TryParse(Date, out double oaDate))
            {
                try
                {
                    Date = DateTime.FromOADate(oaDate).ToString(Formate);
                }
                catch
                {
                    Date = DateTime.MinValue.ToString(Formate);
                }
            }

            string[] parts = Date.Trim().Replace("-", "/").Split("/");

            if (parts.Length != 3)
                return null;

            int year;
            int month;
            int day;
            switch (Formate)
            {
                case "dd/MM/yyyy":
                    if (int.TryParse(parts[2], out year) && year > 2500)
                    {
                        year -= 543;
                    }
                    else if (!int.TryParse(parts[2], out year))
                    {
                        return null;
                    }

                    if (!int.TryParse(parts[1], out month))
                        return null;

                    if (!int.TryParse(parts[0], out day))
                        return null;

                    break;

                case "yyyy-MM-dd":
                    if (int.TryParse(parts[0], out year) && year > 2500)
                    {
                        year -= 543;
                    }
                    else if (!int.TryParse(parts[0], out year))
                    {
                        return null;
                    }

                    if (!int.TryParse(parts[1], out month))
                        return null;

                    if (!int.TryParse(parts[2], out day))
                        return null;
                    break;

                default:
                    return null;
            }

            if (month < 1 || month > 12)
                month = 1;

            int maxDay = DateTime.DaysInMonth(year, month);

            if (day < 1)
                day = 1;
            else if (day > maxDay)
                day = maxDay;

            var normalDate = $"{(day >= 1 && day <= 9 ? $"0{day}" : day)}/{(month >= 1 && month <= 9 ? $"0{month}" : month)}/{(year > 2500 ? year-543 : year)}";
            if (DateTime.TryParseExact(normalDate, "dd/MM/yyyy", CultureInfo.InvariantCulture, DateTimeStyles.None, out DateTime parsedDate))
            {
                return parsedDate;
            }

            return null;
        }
    }
}