using System;
using System.Globalization;

namespace JalaliCalendar
{
    public static class Jalali
    {
        private static readonly PersianCalendar persiancalendar = new PersianCalendar();

        public static string ToPersianDate(this DateTime date)
        {
            return $"{persiancalendar.GetYear(date)}/{persiancalendar.GetMonth(date):00}/{persiancalendar.GetDayOfMonth(date):00}";
        }

        public static DateTime ToGregorianDate(string persianDate)
        {
            persianDate = ConvertToEnglishDigits(persianDate);

            var parts = persianDate.Split('/');
            if (parts.Length != 3)
                throw new FormatException($"فرمت تاریخ اشتباه است. ورودی: {persianDate}. مثال صحیح: 1404/07/15");

            if (!int.TryParse(parts[0], out int year) ||
                !int.TryParse(parts[1], out int month) ||
                !int.TryParse(parts[2], out int day))
            {
                throw new FormatException($"تاریخ نامعتبر: {persianDate}");
            }

            return persiancalendar.ToDateTime(year, month, day, 0, 0, 0, 0);
        }

        public static DateTime ToGregorianDate(DateTime persianDateTime)
        {
            var persianCalendar = new PersianCalendar();
            int year = persianCalendar.GetYear(persianDateTime);
            int month = persianCalendar.GetMonth(persianDateTime);
            int day = persianCalendar.GetDayOfMonth(persianDateTime);

            return persianCalendar.ToDateTime(year, month, day,
                persianDateTime.Hour, persianDateTime.Minute, persianDateTime.Second, 0);
        }

        private static string ConvertToEnglishDigits(string input)
        {
            if (string.IsNullOrEmpty(input))
                return input;

            var result = input;

            char[] persianDigits = { '۰', '۱', '۲', '۳', '۴', '۵', '۶', '۷', '۸', '۹' };
            char[] englishDigits = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' };

            for (int i = 0; i < 10; i++)
            {
                result = result.Replace(persianDigits[i], englishDigits[i]);
            }

            char[] arabicDigits = { '٠', '١', '٢', '٣', '٤', '٥', '٦', '٧', '٨', '٩' };

            for (int i = 0; i < 10; i++)
            {
                result = result.Replace(arabicDigits[i], englishDigits[i]);
            }

            return result;
        }
    }
}