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

namespace SvetoforVKBot.Models.Commands.LK.Menu.Products
{
    public class ShowProductCaruselMain
    {
        private const string PHOTOIDNEXT = "-194717824_457239273_446146426236760985";
        //{"id": 457239273, "owner_id": -194717824, "access_key": "446146426236760985"}
        public void Execute(RootObject update, VkApi client, SvetoforVKBot.Data.SvetoforVKBotEntities db, int curCategory, int curProduct, int curWay)
        //curCategory - id Categories, curProduct - порядковый номер в массиве продуктов, curWay - для showProductCarusel направление навигации
        {
            MessagesSendParams @params = new MessagesSendParams();
            var chatId = update.@object.message.from_id;
            int i = 0;
            int prevCatalog = 0, nextCatalog = 0;
            int naviState = 0;
            double sum = 0;
            string desc = "";
            //int curDay = (int)DateTime.Now.DayOfWeek;
            //if (curDay == 0) curDay = 7;

            List<CategoriesDostavka> categories = new List<CategoriesDostavka>();
            List<ProductsDostavka> products = new List<ProductsDostavka>();
            var row = new List<MessageKeyboardButton>();
            var listButtons = new List<ReadOnlyCollection<MessageKeyboardButton>>();
            TemplateBuilder templateBuilder = new TemplateBuilder();
            CarouselElementAction carouselElementAction = new CarouselElementAction();
            carouselElementAction.Type = CarouselElementActionType.OpenPhoto;

            try
            {
                var user = db.Users.Single(usr => usr.chatId == chatId);
                var cartObject = JsonConvert.DeserializeObject<CartObject>(user.cart);
                int curDay = user.day;

                //SqlCommand getCart = new SqlCommand("SELECT cart, day, colorId 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());
                //int curDay = Convert.ToInt32(rgetCart["day"]);
                //int colorId = Convert.ToInt32(rgetCart["colorId"]);
                //rgetCart.Close();

                if (curDay == 8) curDay = (int)DateTime.Now.DayOfWeek;

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

                categories = db.CategoriesDostavkas.ToList().ConvertAll<CategoriesDostavka>(c =>
                    new CategoriesDostavka()
                    {
                        categoryId = c.categoryId,
                        name = c.name,
                        btnName = c.btnName,
                        kbColor = c.kbColor,
                    });


                //SqlCommand getCategories = new SqlCommand("SELECT * FROM CategoriesDostavka;", Con);
                //getCategories.Parameters.AddWithValue("@chatId", chatId);
                //SqlDataReader rgetCategories = getCategories.ExecuteReader();
                //while (rgetCategories.Read())
                //    categories.Add(new CategoriesDostavka()
                //    {
                //        categoryId = Convert.ToInt32(rgetCategories["categoryId"]),
                //        name = rgetCategories["name"].ToString(),
                //        btnName = rgetCategories["btnName"].ToString(),
                //        kbColor = rgetCategories["kbColor"].ToString(),
                //    });
                //rgetCategories.Close();


                products = db.ProductsDostavkas.Where(p => p.categoryId == curCategory &&
                                JsonConvert.DeserializeObject<List<int>>(p.weekDays).Exists(day => day == curDay)).
                                 ToList().ConvertAll<ProductsDostavka>(e => new ProductsDostavka()
                                 {
                                     id = e.id,
                                     article = e.article,
                                     colorId = e.colorId,
                                     categoryId = e.categoryId,
                                     name = e.name,
                                     fullName = e.fullName,
                                     description = e.description,
                                     descriptionCarousel = e.descriptionCarousel,
                                     price = Convert.ToDouble(e.price),
                                     photo = e.photo,
                                     photoCarousel = e.photoCarousel,
                                     additions = JsonConvert.DeserializeObject<List<string>>(e.additions),
                                     recommends = JsonConvert.DeserializeObject<List<string>>(e.recommends),
                                 });

                //SqlCommand getProducts = new SqlCommand("SELECT * FROM ProductsDostavka WHERE categoryId = @categoryId;", Con);
                //getProducts.Parameters.AddWithValue("@categoryId", curCategory);
                ////getProducts.Parameters.AddWithValue("@colorId", colorId);
                //SqlDataReader rgetProducts = getProducts.ExecuteReader();
                //while (rgetProducts.Read())
                //{
                //    var weekDays = JsonConvert.DeserializeObject<List<int>>(rgetProducts["weekDays"].ToString());
                //    foreach (int weekDay in weekDays)
                //    {
                //        if (weekDay == curDay)
                //        {
                //            products.Add(new ProductsDostavka()
                //            {
                //                id = Convert.ToInt32(rgetProducts["id"]),
                //                article = rgetProducts["article"].ToString(),
                //                colorId = Convert.ToInt32(rgetProducts["colorId"]),
                //                categoryId = Convert.ToInt32(rgetProducts["categoryId"]),
                //                name = rgetProducts["name"].ToString(),
                //                fullName = rgetProducts["fullName"].ToString(),
                //                descriptionCarousel = rgetProducts["descriptionCarousel"].ToString(),
                //                price = Convert.ToInt32(rgetProducts["price"]),
                //                photo = rgetProducts["photo"].ToString(),
                //                photoCarousel = rgetProducts["photoCarousel"].ToString(),
                //                //weight = rgetProducts["weight"].ToString(),
                //            });
                //        }
                //    }
                //}
                //rgetProducts.Close();

                nextCatalog = curProduct + 9;
                prevCatalog = curProduct - 9;

                if (curProduct > 0 && products.Count > 6)
                {
                    if (nextCatalog > products.Count) nextCatalog = products.Count - (products.Count - curProduct);

                    if (prevCatalog < 0) prevCatalog = 0;
                }

                for (i = curProduct; i < products.Count; i++)
                {
                    var jsPhoto = JsonConvert.DeserializeObject<CatalogPhotoObject>(products[i].photoCarousel);

                    desc = products[i].descriptionCarousel; //+ " " + products[i].weight;
                    if (desc.Length > 80) desc = desc.Substring(0, 77) + "..."; //desc.Substring(0, 77)

                    templateBuilder.AddTemplateElement(new CarouselElement()
                    {
                        Title = products[i].fullName,
                        Description = desc,
                        PhotoId = jsPhoto.owner_id + "_" + jsPhoto.id + "_" + jsPhoto.access_key,
                        Buttons = new List<MessageKeyboardButton>()
                        {
                            new MessageKeyboardButton(){
                                Action = new MessageKeyboardButtonAction(){ Label = "Подробнее",
                                    Payload = "{\"button\":\"selectAddToCart-" + curCategory + "-" + i + "\"}",
                                    Type = KeyboardButtonActionType.Text },
                                Color = KeyboardButtonColor.Default
                            },
                        },
                        Action = carouselElementAction,
                    });

                    if (templateBuilder.Elements.Count == 9 && products.Count > 10)
                        break;
                }

                if (products.Count > 10)
                {
                    switch (curWay)
                    {
                        case 1:
                            if (curProduct < (products.Count - 9))
                                naviState = 1;
                            else
                                naviState = 2;
                            break;
                        case 2:
                            if (curProduct == 0)
                                naviState = 1;
                            else
                                naviState = 2;
                            break;
                        default:
                            naviState = 2;
                            break;
                    }

                    switch (naviState)
                    {
                        case 1:
                            templateBuilder.AddTemplateElement(new CarouselElement()
                            {
                                Title = ".",
                                Description = ".",
                                PhotoId = PHOTOIDNEXT,
                                Buttons = new List<MessageKeyboardButton>()
                                {
                                    new MessageKeyboardButton() {
                                        Action = new MessageKeyboardButtonAction(){ Label = ">> Следующие " + (products.Count - nextCatalog).ToString(),
                                            Payload = "{\"button\":\"selectProduct-" + products[nextCatalog].categoryId + "-" + nextCatalog + "-1\"}",
                                            Type = KeyboardButtonActionType.Text },
                                        Color = KeyboardButtonColor.Primary
                                    },
                                },
                                Action = carouselElementAction,
                            });
                            break;

                        case 2:
                            templateBuilder.AddTemplateElement(new CarouselElement()
                            {
                                Title = ".",
                                Description = ".",
                                PhotoId = PHOTOIDNEXT,
                                Buttons = new List<MessageKeyboardButton>()
                                {
                                    new MessageKeyboardButton() {
                                        Action = new MessageKeyboardButtonAction(){ Label = "<< Предыдущие " + curProduct,
                                            Payload = "{\"button\":\"selectProduct-" + products[prevCatalog].categoryId + "-" + prevCatalog + "-2\"}",
                                            Type = KeyboardButtonActionType.Text },
                                        Color = KeyboardButtonColor.Primary
                                    },
                                },
                                Action = carouselElementAction,
                            });
                            break;
                    }
                }

                @params.Template = templateBuilder.Build();
                @params.Message = "😍";
                @params.UserId = chatId;
                @params.RandomId = GetRandomId();
                client.Messages.SendAsync(@params);

            }
            catch (Exception ee)
            {
                @params.Message = "‼Ошибка в ShowProductCaruselMain: " + 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);
        }
    }
}
