using SvetoforVKBot.Models.Updates;
using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using VkNet;
using VkNet.Model.RequestParams;
using System.Security.Cryptography;
using VkNet.Model.Keyboard;
using VkNet.Model.Attachments;
using VkNet.Enums.SafetyEnums;
using System.Collections.ObjectModel;
using System.Threading;
using System.Linq;
using SvetoforVKBot.App_Start;
using System.Configuration;

namespace SvetoforVKBot.Models.Dop
{
    public class GetAskQuestionsCommand
    {
        private const int MODER = 59111081; //35688505; //59111081
        public void Execute(RootObject update, VkApi client, SvetoforVKBot.Data.SvetoforVKBotEntities db)
        {
            MessagesSendParams @params = new MessagesSendParams();
            MessagesSendParams @params2 = new MessagesSendParams();
            var chatId = update.@object.message.from_id;
            var keyboardBuilder = new KeyboardBuilder().Clear();

            try
            {
                var user = db.Users.Single(usr => usr.chatId == chatId);
                user.tag = "Задал вопрос";
                db.SaveChanges();

                keyboardBuilder
                    .AddButton("В начало", "startPL", KeyboardButtonColor.Positive);

                @params.Keyboard = keyboardBuilder.Build();
                @params.Message = "Вопрос отправлен 📩 \n" +
                    "✅Ответим в течение часа";

                @params.UserId = chatId;
                @params.RandomId = GetRandomId();
                client.Messages.Send(@params);

                Thread.Sleep(1000);

                @params2.Message = "❓Вопрос. \nСсылка на диалог: " + ((WebConfiguration)ConfigurationManager.GetSection("VKApi")).GroupDialogsLink  + chatId;

                List<long> listFrwMsg = new List<long>() { update.@object.message.id };
                @params2.UserId = MODER;
                @params2.ForwardMessages = listFrwMsg;
                @params2.RandomId = GetRandomId();
                client.Messages.Send(@params2);
            }
            catch (Exception ee)
            {
                @params.Message = "‼Ошибка в GetAskQuestionsCommand: " + 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);
        }
    }
}
