using System;
using System.Data.SqlClient;
using SvetoforVKBot.Models.Updates;
using VkNet;
using VkNet.Enums.SafetyEnums;
using VkNet.Model.Keyboard;
using VkNet.Model.RequestParams;
using System.Text.RegularExpressions;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using Newtonsoft.Json;
using System.Linq;

namespace SvetoforVKBot.Models.Commands.LK.Calculators
{
    public class SelectCalcCcalResultCommand : Command
    {
        public override string Name => "{\"button\":\"selectCalcCcalResult-";

        public override void Execute(RootObject update, VkApi client, SvetoforVKBot.Data.SvetoforVKBotEntities db)
        {
        }

        public override void ExecutePL(RootObject update, VkApi client, SvetoforVKBot.Data.SvetoforVKBotEntities db)
        {
            var chatId = update.@object.message.from_id;
            MessagesSendParams @params = new MessagesSendParams();
            Regex regex = new Regex("[^0-9]");
            string msg = "";
            var keyboardBuilder = new KeyboardBuilder().Clear();
            int age = 0;
            int genderCoef = 0;
            double kkalResult = 0;
            double kkalResultLow = 0;
            double kkalResultHigh = 0;
            double colorPercent = 0;
            double dayCoef = 0;
            double curDayKkal = 0;
            try
            {
                string[] payload = update.@object.message.payload.Split('-');
                int curColor = Convert.ToInt32(regex.Replace(payload[1], ""));

                Dictionary<int, string> days = new Dictionary<int, string>(7);
                days.Add(1, "Понедельник");
                days.Add(2, "Вторник");
                days.Add(3, "Среда");
                days.Add(4, "Четверг");
                days.Add(5, "Пятница");
                days.Add(6, "Суббота");
                days.Add(7, "Воскресенье");

                int curDay = (int)DateTime.Now.DayOfWeek;
                if (curDay == 0) curDay = 7;

                var user = db.Users.Single(usr => usr.chatId == chatId);
                List<int> sportDays = JsonConvert.DeserializeObject<List<int>>(user.sportDays);

                string cons = "✅Прошёл консультацию";

                if ((DateTime.Now.Month >= user.birthday.Month) && (DateTime.Now.Day >= user.birthday.Day))
                    age = DateTime.Now.Year - user.birthday.Year;
                else
                    age = DateTime.Now.Year - user.birthday.Year - 1;

                if (user.weight == 0 || user.height == 0)
                {
                    keyboardBuilder
                        .AddButton("📝Редактировать данные", "selectEditData-0", KeyboardButtonColor.Primary)
                        .AddLine()
                        .AddButton("Назад", "startPL", KeyboardButtonColor.Default);

                    @params.Message = "Для подсчёта калорий не хватает данных о росте/весе.\n" +
                        "Нажмите \"📝Редактировать данные\" и заполните показатели.";

                    @params.Keyboard = keyboardBuilder.Build();
                    @params.UserId = chatId;
                    @params.RandomId = GetRandomId();
                    client.Messages.SendAsync(@params);
                    return;
                }


                if (user.gender == 1)
                {
                    genderCoef = 5;
                    //cons = "✅Прошёл консультацию";
                }
                else
                {
                    genderCoef = -161;
                    //cons = "✅Прошла консультацию";
                }
                switch (user.track)
                {
                    case 1: //не изменяя веса
                        colorPercent = 1;
                        break;
                    case 2:
                        colorPercent = 0.75; //1 - 15%
                        break;
                    case 3:
                        colorPercent = 1.2; //1 - 15%
                        break;
                    default:
                        colorPercent = 1;
                        break;
                }
                @params.Message = "Ваш результат:\n\n";

                for (int i = 1; i <= 7; i++)
                {                    
                    switch (i)
                    {
                        case 2:
                            dayCoef = 0.8;
                            break;

                        case 3:
                            dayCoef = 1.2;
                            break;

                        case 5:
                            dayCoef = 0.9;
                            break;

                        case 6:
                            dayCoef = 1.1;
                            break;

                        default:
                            dayCoef = 1;
                            break;
                    }

                    kkalResult = Math.Round((((10 * user.weight) + (6.25 * user.height) - (5 * age) + genderCoef) * user.activityCoef) * colorPercent * dayCoef);
                    kkalResultHigh = Math.Round(kkalResult * 1.2);
                    kkalResultLow = Math.Round(kkalResult * 0.9);

                    if (i == curDay)
                    {
                        @params.Message += $"⭐ {days[i]}: {kkalResultLow}-{kkalResultHigh} ккал\n";
                        curDayKkal = kkalResult;
                    }
                    else
                        @params.Message += $"{days[i]}: {kkalResultLow}-{kkalResultHigh} ккал\n";
                }
                //kkalResult = Math.Round((((10 * weight) + (6.25 * height) - (5 * age) + genderCoef) * activityCoef) * colorPercent);

                keyboardBuilder.AddButton("Личный кабинет", "startPL", KeyboardButtonColor.Default);

                user.kkal = Convert.ToInt32(curDayKkal);
                db.SaveChanges();

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