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

namespace SvetoforVKBot.Models.Commands.LK.Cart
{
    public class ShowCart
    {
        public void Execute(RootObject update, VkApi client, SvetoforVKBot.Data.SvetoforVKBotEntities db, int curCart) //curCart - порядковый номер в массиве корзины
        {
            MessagesSendParams @params = new MessagesSendParams();
            int cartCount = 0;
            var chatId = update.@object.message.from_id;
            string msg = "";
            //string voronka = "";
            List<CategoriesDostavka> categories = new List<CategoriesDostavka>();
            List<ProductsDostavka> products = new List<ProductsDostavka>();
            int i = 0;
            int j = 0;
            int prevCart = 0, nextCart = 0;
            double sum = 0;
            double fullSum = 0;
            string label = "";
            var keyboardBuilder = new KeyboardBuilder().Clear();
            int kkals = 0;
            try
            {
                var user = db.Users.Single(usr => usr.chatId == chatId);
                var cartObject = JsonConvert.DeserializeObject<CartObject>(user.cart);


                //SqlCommand getCart = new SqlCommand("SELECT cart, voronka FROM Users WHERE chatId = @chatId;", Con);
                //getCart.Parameters.AddWithValue("@chatId", chatId);
                //SqlDataReader rgetCart = getCart.ExecuteReader();
                //rgetCart.Read();
                //var cartObject = JsonConvert.DeserializeObject<CartObject>(rgetCart["cart"].ToString());
                //voronka = rgetCart["voronka"].ToString();
                //rgetCart.Close();

                //cartObject.orders.RemoveAll(o => o.article.StartsWith("00-"));
                cartObject.dostavkaCost = 100;

                //if (cartObject.orders.Count == 0)
                //{
                //    msg = "Корзина пуста.\n📋Возвращаю в основное меню";
                //    ShowMenuDostavka showMenuDostavka = new ShowMenuDostavka();
                //    showMenuDostavka.Execute(update, client, Con, msg, 1, 0);
                //    return;
                //}

                if (curCart >= cartObject.orders.Count)
                {
                    curCart = cartObject.orders.Count - 1;
                    prevCart = curCart - 1;
                    nextCart = 0;
                }
                else
                {
                    prevCart = curCart - 1;
                    nextCart = curCart + 1;
                }
                if ((curCart + 1) == cartObject.orders.Count)
                {
                    prevCart = curCart - 1;
                    nextCart = 0;
                }
                if (curCart == 0)
                {
                    prevCart = cartObject.orders.Count - 1;
                    nextCart = curCart + 1;
                }
                string promo = "";
                msg = "Ваша корзина: \n";

                double sumCheck = 0;
                foreach (var o in cartObject.orders)
                {
                    sumCheck += o.price * o.number;
                }

                for (i = 0; i < cartObject.orders.Count; i++)
                {
                    cartCount++;
                    switch (cartObject.orders[i].id)
                    {                      

                        default:
                            msg += (i + 1).ToString() + ". " +
                                cartObject.orders[i].fullname + " - " + cartObject.orders[i].kkal + " ккал. " +
                                cartObject.orders[i].number + " шт. " +
                                (cartObject.orders[i].price * cartObject.orders[i].number).ToString() + " ₽ \n";
                            sum += cartObject.orders[i].price * cartObject.orders[i].number;
                            kkals += cartObject.orders[i].kkal * cartObject.orders[i].number;
                            break;
                    }
                    //msg += (i + 1).ToString() + ". " +
                    //    cartObject.orders[i].fullname + " - " +
                    //    cartObject.orders[i].number + " шт. " +
                    //    (cartObject.orders[i].price * cartObject.orders[i].number).ToString() + " ₽ \n";


                    /*cartCount++;
                    for (j = 0; j < cartObject.orders.Count; j++)
                    {
                        msg += " " + cartCount.ToString() + "." + (j + 1).ToString() + " Доп - " +
                        cartObject.orders[i].addition[j].fullname + " - " +
                        cartObject.orders[i].addition[j].number + " шт. " +
                        (cartObject.orders[i].addition[j].price * cartObject.orders[i].addition[j].number).ToString() + " ₽ \n";
                    }
                    */                   

                }

                
                    fullSum = sum;

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

                //SqlCommand updCart = new SqlCommand("UPDATE Users SET cart = @cart WHERE chatId = @chatId;", Con);
                //updCart.Parameters.AddWithValue("@chatId", chatId);
                //updCart.Parameters.AddWithValue("@cart", JsonConvert.SerializeObject(cartObject));
                //updCart.ExecuteNonQuery();

                msg += "\n" +
                    "Итого: " + fullSum + " ₽ | " + kkals + " ккал.";

                label = cartObject.orders[curCart].name + " " +
                        cartObject.orders[curCart].price + " ₽ * " +
                        cartObject.orders[curCart].number + " = " +
                        (cartObject.orders[curCart].price * cartObject.orders[curCart].number).ToString() + " ₽";

                if (label.Length > 40)
                    label = cartObject.orders[curCart].name + " " +
                            (cartObject.orders[curCart].price * cartObject.orders[curCart].number).ToString() + " ₽";

                keyboardBuilder
                    .AddButton(label, "selectCart-" + curCart, KeyboardButtonColor.Default)
                    .AddLine()
                    .AddButton("-", "selectEditCart-1-" + curCart, KeyboardButtonColor.Default)
                    .AddButton(cartObject.orders[curCart].number + " шт", "selectCartCount-" + curCart, KeyboardButtonColor.Default)
                    .AddButton("+", "selectEditCart-2-" + curCart, KeyboardButtonColor.Default)
                    .AddButton("🗑Очистить", "selectConfirmClearCart", KeyboardButtonColor.Default)
                    .AddLine()
                    .AddButton("<<", "selectCart-" + prevCart, KeyboardButtonColor.Primary)
                    .AddButton((curCart + 1).ToString() + "/" + cartObject.orders.Count, "selectCart-" + curCart, KeyboardButtonColor.Default)
                    .AddButton(">>", "selectCart-" + nextCart, KeyboardButtonColor.Primary);               

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


                @params.Message = msg;
                @params.UserId = chatId;
                @params.Keyboard = keyboardBuilder.Build();
                @params.DontParseLinks = true;
                @params.RandomId = GetRandomId();
                client.Messages.SendAsync(@params);
            }
            catch (Exception ee)
            {
                @params.Message = "‼Ошибка в ShowCart: " + 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);
        }
    }
}