using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using SvetoforVKBot.App_Start;
using SvetoforVKBot.Models;
using SvetoforVKBot.Models.Commands.Admin;
using SvetoforVKBot.Models.Updates;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data.SqlClient;
using System.Linq;
using System.Net.Http;
using System.Security.Cryptography;
using System.Text;
using System.Threading;
using System.Web.Mvc;
using VkNet;
using VkNet.Enums.SafetyEnums;
using VkNet.Model;
using VkNet.Model.Attachments;
using VkNet.Model.Keyboard;
using VkNet.Model.RequestParams;

namespace SvetoforVKBot.Controllers
{
    public class SportDaysController : Controller
    {
        // Подключаем контекст базы данных
        private SvetoforVKBot.Data.SvetoforVKBotEntities db = new SvetoforVKBot.Data.SvetoforVKBotEntities();
        protected override void Dispose(bool disposing)
        {
            db.Dispose();
            base.Dispose(disposing);
        }

        // GET: SportDays
        public HttpStatusCodeResult Execute()
        {
            MessagesSendParams @params = new MessagesSendParams();
            MessagesSendParams @params2 = new MessagesSendParams();
            HttpStatusCodeResult httpResult = new HttpStatusCodeResult(200);

            var client = new VkApi();
            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>();
            string msg = "";
            try
            {
                client.AuthorizeAsync(new ApiAuthParams
                {
                    AccessToken = ((WebConfiguration)ConfigurationManager.GetSection("VKApi")).Token
                });

                //if (DateTime.Now.DayOfWeek == DayOfWeek.Monday && DateTime.Now.Hour == 9)
                if (DateTime.Now.DayOfWeek == DayOfWeek.Monday && DateTime.Now.Hour == 13)
                {

                    ids = db.Users.Where(e => e.notifyCount > 0 && e.reg == 1 && e.sportDays != "[]" && e.activityKind != 3).ToList().ConvertAll(e => e.chatId);

                    @params.Message = "Добрый день☀\n" +
                        "Сегодня понедельник - самое время обновить график тренировок на неделю.\n" +
                        "Нажмите кнопку \"Обновить\" 😉";

                    keyboardBuilder
                            .AddButton("Обновить", "selectUpdateSportDays", KeyboardButtonColor.Positive)
                            .AddLine()
                            .AddButton("Личный кабинет", "startPL", KeyboardButtonColor.Primary)
                            .SetInline();

                    foreach (var id in ids)
                    {
                        @params.Keyboard = keyboardBuilder.Build();
                        @params.UserId = id;
                        @params.RandomId = GetRandomId();
                        client.Messages.SendAsync(@params);

                        Thread.Sleep(500);
                    }
                }
          
                return httpResult;
            }
            catch (Exception ee)
            {
                @params.Message = "‼Ошибка в SportDaysController: " + ee.Message;
                @params.Attachments = null;
                @params.Keyboard = null;
                @params.UserId = 59111081; 
                @params.RandomId = GetRandomId();
                client.Messages.Send(@params);
                return httpResult;
            }
        }

        private static readonly RandomNumberGenerator Rng = RandomNumberGenerator.Create();
        private int GetRandomId()
        {

            var intBytes = new byte[4];

            Rng.GetBytes(intBytes);

            return BitConverter.ToInt32(intBytes, 0);
        }
    }
}