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

namespace SvetoforVKBot.Models.Commands.LK.Cart
{
    public class SelectAddToCartCommand : Command
    {
        public override string Name => "{\"button\":\"selectAddToCart-";

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

        public override void ExecutePL(RootObject update, VkApi client, SvetoforVKBot.Data.SvetoforVKBotEntities db)
        {
            MessagesSendParams @params = new MessagesSendParams();
            var chatId = update.@object.message.from_id;
            string msg = "";
            double sum = 0;
            string backPL = "startPL";
            Regex regex = new Regex("[^0-9]");
            List<ProductsDostavka> products = new List<ProductsDostavka>();
            List<ProductsDostavka> souses = new List<ProductsDostavka>();
            ShowPersonalMenuCarusel showProductCaruselMain = new ShowPersonalMenuCarusel();
            var keyboardBuilder = new KeyboardBuilder().Clear();
            int kkals = 0;
            try
            {
                string[] payload = update.@object.message.payload.Split('-');
                int curCategory = Convert.ToInt32(regex.Replace(payload[1], ""));
                int curProduct = Convert.ToInt32(regex.Replace(payload[2], ""));
                int curDayKkal = Convert.ToInt32(regex.Replace(payload[3], ""));
                int curDay = (int)DateTime.Now.DayOfWeek;
                if (curDay == 0) curDay = 7;

                var user = db.Users.Single(usr => usr.chatId == chatId);
                var cartObject = JsonConvert.DeserializeObject<CartObject>(user.cart);

                var prodDb = db.ProductsDostavkas.Where(p => 
                            p.id == curProduct &&
                            JsonConvert.DeserializeObject<List<int>>(p.weekDays).Exists(e => e == curDay));
                products = prodDb.ToList().ConvertAll<ProductsDostavka>(el => new ProductsDostavka() 
                {
                    id = el.id,
                    idIiko = el.idIiko,
                    article = el.article,
                    categoryId = el.categoryId,
                    name = el.name,
                    fullName = el.fullName,
                    description = el.description,
                    price = Convert.ToDouble( el.price),
                    photo = el.photo,
                    additions = JsonConvert.DeserializeObject<List<string>>(el.additions),
                    recommends = JsonConvert.DeserializeObject<List<string>>(el.recommends),
                    kkal = el.kkal,
                });
                
                var orderPizza = new Order();
                var orderSous = new Order();
                if (cartObject.orders.Exists(o => o.id.Equals(curCategory + "-" + curProduct)))
                    cartObject.orders.Find(o => o.id.Equals(curCategory + "-" + curProduct)).number++;
                else
                {
                    var order = new Order()
                    {
                        id = curCategory + "-" + curProduct,
                        idIiko = products[0].idIiko,
                        fullname = products[0].fullName,
                        name = products[0].name,
                        price = products[0].price,
                        number = 1,
                        article = products[0].article,
                        kkal = products[0].kkal,
                    };
                    cartObject.orders.Add(order);

                }

                user.cart = JsonConvert.SerializeObject(cartObject);
                db.SaveChanges();

                foreach (var o in cartObject.orders)
                {
                    sum += o.price * o.number;
                    kkals += o.kkal * o.number;
                }

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

                if (cartObject.orders.Count > 0)
                {
                    keyboardBuilder
                        .AddButton("Личный кабинет", "startPL", KeyboardButtonColor.Default)
                        .AddButton("Корзина: " + sum + " р", "selectCart-0", KeyboardButtonColor.Negative);
                }
                else
                {
                    keyboardBuilder
                        .AddButton("Личный кабинет", "startPL", KeyboardButtonColor.Default);
                }
                if (update.@object.client_info.carousel == true)
                {
                    msg = "✅ " + products.Find(p => p.id == curProduct).fullName + " добавлен в корзину.";

                }

                //@params.Template = templateBuilder.Build();
                @params.Keyboard = keyboardBuilder.Build();
                @params.Message = msg;
                @params.UserId = chatId;
                @params.RandomId = GetRandomId();
                client.Messages.SendAsync(@params);
                //else
                //{
                //    switch (curCategory)
                //    {
                //        case 1:
                //            if (update.@object.client_info.carousel == true)
                //                showProductCaruselDouble.Execute(update, client, Con, curCategory, curProduct);
                //            else
                //                showProductDouble.Execute(update, client, Con, curCategory, curProduct, 2);
                //            break;

                //        default:
                //            if (update.@object.client_info.carousel == true)
                //                showProductCaruselMain.Execute(update, client, Con, curCategory, curProduct, 1);
                //            else
                //                showProductMain.Execute(update, client, Con, curCategory, curProduct, 0, 2);
                //            break;
                //    }
                //}
            }
            catch (Exception ee)
            {
                @params.Message = "‼Ошибка в SelectAddToCartCommand: " + ee.Message;
                @params.Attachments = null;
                @params.Keyboard = null;
                @params.UserId = 59111081;
                @params.RandomId = GetRandomId();
                client.Messages.SendAsync(@params);
            }
        }
    }
}