using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Data.SqlClient;
using System.Globalization;
using System.Linq;
using System.Security.Cryptography;
using SvetoforVKBot.Models.Updates;
using VkNet;
using VkNet.Enums.SafetyEnums;
using VkNet.Model.Keyboard;
using VkNet.Model.RequestParams;

namespace SvetoforVKBot.Models.Commands.Registration
{
    public class ShowCalendar
    {
        public void Execute(RootObject update, VkApi client, SvetoforVKBot.Data.SvetoforVKBotEntities db, DateTime curDateTime)
        {
            MessagesSendParams @params = new MessagesSendParams();
            var chatId = update.@object.message.from_id;

            string tag = "";
            string str = "";
            string month = "";
            string plNext = "";
            string plBack = "";
            int i = 0, j = 0;
            int weeks = 5, days = 1, dw = 1;
            DateTime dt, dt1, dt2, dt3;
            dt2 = new DateTime(curDateTime.Year, curDateTime.Month, 1);
            dt3 = new DateTime(curDateTime.Year, curDateTime.Month, 1);
            var row = new List<MessageKeyboardButton>();
            var listRows = new List<List<MessageKeyboardButton>>();
            var listButtons = new List<ReadOnlyCollection<MessageKeyboardButton>>();

            try
            {
                for (i = 1; i <= 7; i++)
                {
                    switch (i)
                    {
                        case 1:
                            str = "Пн";
                            break;
                        case 2:
                            str = "Вт";
                            break;
                        case 3:
                            str = "Ср";
                            break;
                        case 4:
                            str = "Чт";
                            break;
                        case 5:
                            str = "Пт";
                            break;
                        case 6:
                            str = "Сб";
                            break;
                        case 7:
                            str = "Вс";
                            break;
                    }

                    row = new List<MessageKeyboardButton>()
                    {
                        new MessageKeyboardButton() {
                            Action = new MessageKeyboardButtonAction(){ Label = str,
                                Type = KeyboardButtonActionType.Text },
                            Color = KeyboardButtonColor.Default
                        },
                    };
                    listRows.Add(new List<MessageKeyboardButton>(row));
                }

                days = curDateTime.Day;
                dt = new DateTime(curDateTime.Year, curDateTime.Month, 1);
                if ((DateTime.DaysInMonth(curDateTime.Year, curDateTime.Month) == 28) && (dt.DayOfWeek == DayOfWeek.Monday))
                    weeks = 4;
                if ((DateTime.DaysInMonth(curDateTime.Year, curDateTime.Month) >= 30) && (dt.DayOfWeek == DayOfWeek.Sunday))
                    weeks = 6;

                for (i = 1; i <= weeks; i++)
                {
                    row = new List<MessageKeyboardButton>();
                    if (days > DateTime.DaysInMonth(curDateTime.Year, curDateTime.Month)) break;
                    if (i == 4)
                        dt2 = new DateTime(curDateTime.Year, curDateTime.Month, days);

                    for (j = 0; j < 7; j++)
                    {
                        if (days <= DateTime.DaysInMonth(curDateTime.Year, curDateTime.Month))
                        {
                            dt = new DateTime(curDateTime.Year, curDateTime.Month, days);
                            dw = getDayOfWeek(dt.DayOfWeek);

                            if ((j + 1) == dw)
                            {
                                if (dt.Date < DateTime.Now.Date)
                                {
                                    str = "·" + days.ToString() + "·";
                                    if (listRows[j].Count < 4)
                                        listRows[j].Add(new MessageKeyboardButton()
                                        {
                                            Action = new MessageKeyboardButtonAction()
                                            {
                                                Label = str,
                                                Payload = "{\"button\":\"selectDate-" + dt.ToShortDateString() + "\"}",
                                                Type = KeyboardButtonActionType.Text
                                            },
                                            Color = KeyboardButtonColor.Primary
                                        });
                                }
                                else
                                if (listRows[j].Count < 4)
                                    listRows[j].Add(
                                        new MessageKeyboardButton()
                                        {
                                            Action = new MessageKeyboardButtonAction()
                                            {
                                                Label = "-" + days.ToString() + "-",
                                                Type = KeyboardButtonActionType.Text
                                            },
                                            Color = KeyboardButtonColor.Default
                                        });
                                days++;
                            }
                            else
                            if (listRows[j].Count < 4)
                                listRows[j].Add(
                                    new MessageKeyboardButton()
                                    {
                                        Action = new MessageKeyboardButtonAction()
                                        {
                                            Label = "·",
                                            Type = KeyboardButtonActionType.Text
                                        },
                                        Color = KeyboardButtonColor.Default
                                    });
                        }
                        else
                        if (listRows[j].Count < 4)
                            listRows[j].Add(
                                new MessageKeyboardButton()
                                {
                                    Action = new MessageKeyboardButtonAction()
                                    {
                                        Label = "·",
                                        Type = KeyboardButtonActionType.Text
                                    },
                                    Color = KeyboardButtonColor.Default
                                });
                    }
                }

                foreach (var lr in listRows)
                    listButtons.Add(new ReadOnlyCollection<MessageKeyboardButton>(lr));

                month = CultureInfo.CurrentCulture.DateTimeFormat.GetMonthName(curDateTime.Month);

                dt1 = new DateTime(DateTime.Now.Year, DateTime.Now.Month, 1);

                if (dt2 == dt3) //генерируем вторую половину месяца
                {
                    plBack = "{\"button\":\"selectDateNavigation-" + dt3.ToShortDateString() + "\"}";
                    plNext = "{\"button\":\"selectDateNavigation-" + dt3.AddMonths(1).ToShortDateString() + "\"}";
                }
                else //генерируем первую половину месяца
                {
                    plBack = "{\"button\":\"selectDateNavigation-" + dt3.AddMonths(-1).AddDays(21 - getDayOfWeek(dt3.AddMonths(-1).DayOfWeek) + 1).ToShortDateString() + "\"}";
                    plNext = "{\"button\":\"selectDateNavigation-" + dt2.ToShortDateString() + "\"}";
                }

                if (dt1.Date > dt2.Date)
                    row = new List<MessageKeyboardButton>()
                    {
                        new MessageKeyboardButton() {
                            Action = new MessageKeyboardButtonAction(){ Label = "<<", Payload = plBack,
                                Type = KeyboardButtonActionType.Text },
                            Color = KeyboardButtonColor.Default
                        },
                        new MessageKeyboardButton() {
                            Action = new MessageKeyboardButtonAction(){ Label = month,
                                Type = KeyboardButtonActionType.Text },
                            Color = KeyboardButtonColor.Default
                        },
                        new MessageKeyboardButton() {
                            Action = new MessageKeyboardButtonAction(){ Label = ">>", Payload = plNext,
                                Type = KeyboardButtonActionType.Text },
                            Color = KeyboardButtonColor.Default
                        },
                    };
                else
                    row = new List<MessageKeyboardButton>()
                    {
                        new MessageKeyboardButton() {
                            Action = new MessageKeyboardButtonAction(){ Label = "<<", Payload = plBack,
                                Type = KeyboardButtonActionType.Text },
                            Color = KeyboardButtonColor.Default
                        },
                        new MessageKeyboardButton() {
                            Action = new MessageKeyboardButtonAction(){ Label = month,
                                Type = KeyboardButtonActionType.Text },
                            Color = KeyboardButtonColor.Default
                        },
                    };
                listButtons.Add(new ReadOnlyCollection<MessageKeyboardButton>(row));

                if (curDateTime.Year < DateTime.Now.Year)
                    row = new List<MessageKeyboardButton>()
                    {
                        new MessageKeyboardButton() {
                            Action = new MessageKeyboardButtonAction(){ Label = "<<", Payload = "{\"button\":\"selectDateNavigation-" + curDateTime.AddYears(-1).ToShortDateString() + "\"}",
                                Type = KeyboardButtonActionType.Text },
                            Color = KeyboardButtonColor.Default
                        },
                        new MessageKeyboardButton() {
                            Action = new MessageKeyboardButtonAction(){ Label = curDateTime.Year.ToString(),
                                Type = KeyboardButtonActionType.Text },
                            Color = KeyboardButtonColor.Default
                        },
                        new MessageKeyboardButton() {
                            Action = new MessageKeyboardButtonAction(){ Label = ">>", Payload = "{\"button\":\"selectDateNavigation-" + curDateTime.AddYears(1).ToShortDateString() + "\"}",
                                Type = KeyboardButtonActionType.Text },
                            Color = KeyboardButtonColor.Default
                        },
                    };
                else
                    row = new List<MessageKeyboardButton>()
                    {
                        new MessageKeyboardButton() {
                            Action = new MessageKeyboardButtonAction(){ Label = "<<", Payload = "{\"button\":\"selectDateNavigation-" + curDateTime.AddYears(-1).ToShortDateString() + "\"}",
                                Type = KeyboardButtonActionType.Text },
                            Color = KeyboardButtonColor.Default
                        },
                        new MessageKeyboardButton() {
                            Action = new MessageKeyboardButtonAction(){ Label = curDateTime.Year.ToString(),
                                Type = KeyboardButtonActionType.Text },
                            Color = KeyboardButtonColor.Default
                        },
                    };
                listButtons.Add(new ReadOnlyCollection<MessageKeyboardButton>(row));

                var user = db.Users.Single(usr => usr.chatId == chatId);

                switch (user.tag)
                {
                    case "Подписчик - Регистрация - ДР - Число":
                        @params.Message = "📅 Выберите дату своего рождения на календаре. \n";

                        break;
                }

                var buttons = new ReadOnlyCollection<ReadOnlyCollection<MessageKeyboardButton>>(listButtons);
                var keyboard = new MessageKeyboard()
                {
                    Buttons = buttons,
                    OneTime = false
                };

                @params.UserId = chatId;
                @params.Keyboard = keyboard;
                @params.RandomId = GetRandomId();
                client.Messages.SendAsync(@params);
            }
            catch (Exception ee)
            {
                @params.Message = "‼Ошибка в ShowCalendarVK: " + ee.Message;
                @params.Attachments = null;
                @params.Keyboard = null;
                @params.UserId = 59111081;
                @params.RandomId = GetRandomId();
                client.Messages.SendAsync(@params);
            }
        }

        private static readonly RandomNumberGenerator Rng = RandomNumberGenerator.Create();
        private int GetRandomId()
        {
            var intBytes = new byte[4];

            Rng.GetBytes(intBytes);

            return BitConverter.ToInt32(intBytes, 0);
        }
        private int getDayOfWeek(DayOfWeek dw)
        {
            switch (dw)
            {
                case DayOfWeek.Monday:
                    return 1;
                case DayOfWeek.Tuesday:
                    return 2;
                case DayOfWeek.Wednesday:
                    return 3;
                case DayOfWeek.Thursday:
                    return 4;
                case DayOfWeek.Friday:
                    return 5;
                case DayOfWeek.Saturday:
                    return 6;
                case DayOfWeek.Sunday:
                    return 7;
            }
            return 1;
        }
    }
}