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

namespace SvetoforVKBot.Models.Commands.LK.Menu.Products
{
    public class ShowProductMain
    {
        public void Execute(RootObject update, VkApi client, SvetoforVKBot.Data.SvetoforVKBotEntities db, int curCategory, int curProduct, int curAddition, int plAction)
        {
            MessagesSendParams @params = new MessagesSendParams();
            var chatId = update.@object.message.from_id;
            int i = 0;
            int index = 0;
            Regex regex = new Regex("[^0-9]");
            int prevCatalog = 0, nextCatalog = 0;
            //double sumCart = 0;
            double sum = 0;
            Additions addition = new Additions();
            //DateTime startDate = new DateTime(2020, 09, 14);
            //DateTime currentDate = DateTime.Now;
            //TimeSpan offset = currentDate - startDate;
            //int curDay = offset.Days % 14 + 1;

            string backPL = "selectMenu-0";

            List<CategoriesDostavka> categories = new List<CategoriesDostavka>();
            List<ProductsDostavka> products = new List<ProductsDostavka>();
            var keyboardBuilder = new KeyboardBuilder().Clear();

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

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

                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,
                    });


                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),
                                 });


                switch (plAction)
                {
                    case 1:
                        var jsPhoto = JsonConvert.DeserializeObject<CatalogPhotoObject>(products[curProduct].photo);
                        List<MediaAttachment> listPhoto = new List<MediaAttachment>()
                        {
                            new VkNet.Model.Attachments.Photo() { Id = jsPhoto.id, OwnerId = jsPhoto.owner_id, AccessKey = jsPhoto.access_key}
                        };
                        @params.Attachments = listPhoto;
                        @params.Message = products[curProduct].fullName + "\n" +
                        products[curProduct].description + "\n"; // + " " + products[curProduct].weight
                        break;
                    case 2:
                        if (curAddition == 0)
                            @params.Message = "✅ " + products[curProduct].fullName + " добавлен в корзину.";
                        else
                        {
                            // Нет таблицы с модификаторами
                            
                            //SqlCommand getAddition = new SqlCommand("SELECT * FROM Modifiers WHERE article = @article;", Con);
                            //getAddition.Parameters.AddWithValue("@article", curAddition);
                            //SqlDataReader rgetAddition = getAddition.ExecuteReader();
                            //if (rgetAddition.HasRows)
                            //{
                            //    rgetAddition.Read();
                            //    addition = new Additions()
                            //    {
                            //        name = rgetAddition["name"].ToString(),
                            //        price = Convert.ToInt32(rgetAddition["price"]),
                            //        fullName = rgetAddition["fullName"].ToString(),
                            //        article = rgetAddition["article"].ToString(),
                            //    };
                            //}
                            //rgetAddition.Close();

                            @params.Message = "✅ " + products[curProduct].fullName + " с " + addition.fullName + " добавлен в корзину.";
                        }
                        break;
                }

                if (curProduct >= products.Count)
                {
                    curProduct = products.Count - 1;
                    prevCatalog = curProduct - 1;
                    nextCatalog = 0;
                }
                else
                {
                    prevCatalog = curProduct - 1;
                    nextCatalog = curProduct + 1;
                }

                if ((curProduct + 1) == products.Count)
                {
                    prevCatalog = curProduct - 1;
                    nextCatalog = 0;
                }
                if (curProduct == 0)
                {
                    prevCatalog = products.Count - 1;
                    nextCatalog = curProduct + 1;
                }
                if (products.Count == 1)
                {
                    prevCatalog = 0;
                    nextCatalog = 0;
                }

                #region keyboard
                //keyboardBuilder
                //    .AddButton("Подробнее", "selectAddToCart-" + curCategory + "-" + curProduct, KeyboardButtonColor.Primary)
                //    .AddLine();

                keyboardBuilder
                    .AddButton("<<", "selectProduct-" + curCategory + "-" + prevCatalog + "-1", KeyboardButtonColor.Primary)
                    .AddButton((curProduct + 1) + "/" + products.Count, "selectProduct-" + curCategory + "-" + curProduct + "-1", KeyboardButtonColor.Default)
                    .AddButton(">>", "selectProduct-" + curCategory + "-" + nextCatalog + "-1", KeyboardButtonColor.Primary)
                    .AddLine();


                keyboardBuilder
                    .AddButton("Вернуться в меню", "selectDayMenu-" + curDay, KeyboardButtonColor.Default)
                    //.AddButton("Корзина: " + sum + " р", "selectCart-0", KeyboardButtonColor.Negative)
                    .AddLine()
                    .AddButton("День недели", "selectMenu-0", KeyboardButtonColor.Default);
                        //.AddLine();


                #endregion keyboard
                /*
                if (products.Count > 10) //14
                {
                    if (curProduct < (products.Count - 10)) index = curProduct + 1;
                    else index = products.Count - 10;
                }
                else index = 0;

                int rowCount = 3;
                
                for (i = index; i < products.Count; i += 2)
                {
                    if (i + 1 < products.Count)
                        keyboardBuilder
                            .AddButton(products[i].name, "selectProduct-" + curCategory + "-" + i.ToString() + "-1", KeyboardButtonColor.Default)
                            .AddButton(products[i + 1].name, "selectProduct-" + curCategory + "-" + (i + 1).ToString() + "-1", KeyboardButtonColor.Default)
                            .AddLine();
                    else
                        keyboardBuilder
                            .AddButton(products[i].name, "selectProduct-" + curCategory + "-" + i.ToString() + "-1", KeyboardButtonColor.Default)
                            .AddLine();
                    rowCount += 1;

                    if (rowCount == 8) break;
                }
                */

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