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 Newtonsoft.Json;
using VkNet.Enums.Filters;
using VkNet.Model.Attachments;
using System.Collections.Generic;
using System.Threading;
using SvetoforVKBot.Models.Dop;
using SvetoforVKBot.Models.Commands;
using System.Linq;

namespace SvetoforVKBot.Models.Commands.LK
{
    public class SelectDayFoodCommand : Command
    {
        public override string Name => "{\"button\":\"selectDayFood\"}";

        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();
            var keyboardBuilder = new KeyboardBuilder().Clear();
            var keyboardBuilder2 = new KeyboardBuilder().Clear();
            DateTime dt = DateTime.Now.AddHours(0);
            List<OrderLog> orders = new List<OrderLog>();
            string highWorkload = "0";
            List<int> ids = new List<int>();
            List<int> ids2 = new List<int>();
            List<int> idsFood = new List<int>();
            List<UserObject> waterNotifiesList = new List<UserObject>();
            string msg = "";

            string name = "";
            int age = 0;
            int genderCoef = 0;
            double kkalResult = 0;
            double colorPercent = 0;
            double dayCoef = 0;
            double curDayKkal = 0;
            double kkalResultLow = 0;
            double kkalResultHigh = 0;
            try
            {
                switch (DateTime.Now.DayOfWeek)
                {
                    case DayOfWeek.Saturday:
                    case DayOfWeek.Sunday:
                        keyboardBuilder
                            .AddButton("Назад", "startPL", KeyboardButtonColor.Default);
                        @params.Message = "Рекомендации по дневному меню доступны с понедельника по пятницу.\n" +
                            "Чтобы вернуться в Личный кабинет, нажмите кнопку \"Назад\"";
                        @params.Keyboard = keyboardBuilder.Build();
                        @params.UserId = chatId;
                        @params.RandomId = GetRandomId();
                        client.Messages.SendAsync(@params);
                        return;
                }

                var user = db.Users.Single(usr => usr.chatId == chatId);
                user.choosenProducts = "[]";
                user.cart = "{\"orders\":[]}";
                db.SaveChanges();


                Dictionary<int, string> tracks = new Dictionary<int, string>(7);
                tracks.Add(1, "Оптимизация питания");
                tracks.Add(2, "Снижение жировой массы");
                tracks.Add(3, "Увеличение мышечной массы");
                tracks.Add(4, "Персональный режим");

                keyboardBuilder.Clear();

                var jsPhones = JsonConvert.DeserializeObject<List<string>>(user.phone);

                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;

                #region ccalCalculator
                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, "Воскресенье");

                Dictionary<int, string> gend = new Dictionary<int, string>(3);
                gend.Add(0, "Мужской");
                gend.Add(1, "Мужской");
                gend.Add(2, "Женский");

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

                int nextDay = curDay + 1;

                if (nextDay == 8)
                    nextDay = 1;

                //if (weight == 0 || 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;
                }
                else
                {
                    genderCoef = -161;
                }
                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;
                }

                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)
                    //if (i == curDay)
                    {
                        curDayKkal = kkalResult;
                    }
                }
                #endregion ccalCalculator


                //@params.Message = "🌙Добрый вечер!\n" +
                //    $"Ваша норма калорий на завтра: {Math.Round(curDayKkal * 0.9)} - {Math.Round(curDayKkal * 1.2)}\n" +
                //    "Мы подготовили для Вас блюда👇🏻";
                @params.Message = //"☀Доброе утро!\n" +
                    $"Ваша норма калорий на сегодня: {Math.Round(curDayKkal * 0.9)} - {Math.Round(curDayKkal * 1.2)}\n" +
                    $"Мы подготовили для Вас блюда👇🏻\n\n";

                keyboardBuilder
                    .AddButton($"Завтрак (до {Math.Round(curDayKkal * 1.2 * 0.3)} ккал)", "selectPersonalMenu-1-" + Math.Round(curDayKkal), KeyboardButtonColor.Primary)
                    .AddLine()
                    .AddButton($"Обед (до {Math.Round(curDayKkal * 1.2 * 0.4)} ккал)", "selectPersonalMenu-2-" + Math.Round(curDayKkal), KeyboardButtonColor.Primary)
                    .AddLine()
                    .AddButton($"Перекус (до {Math.Round(curDayKkal * 1.2 * 0.1)} ккал)", "selectPersonalMenu-3-" + Math.Round(curDayKkal), KeyboardButtonColor.Primary)
                    .AddLine()
                .AddButton($"Ужин (до {Math.Round(curDayKkal * 1.2 * 0.3)} ккал)", "selectPersonalMenu-4-" + Math.Round(curDayKkal), KeyboardButtonColor.Primary)
                .AddLine()
                .AddButton("Личный кабинет", "startPL", KeyboardButtonColor.Default);
                //.SetInline();

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

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