using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
using System.Net.Http;
using System.Security.Cryptography;
using System.Text;
using SvetoforVKBot.Models.Updates;
using VkNet;
using VkNet.Enums.SafetyEnums;
using VkNet.Model.Keyboard;
using VkNet.Model.RequestParams;

namespace SvetoforVKBot.Models.Commands.LK.Reports
{
    public class GetReportCommentCommand
    {
        public void Execute(RootObject update, VkApi client, SvetoforVKBot.Data.SvetoforVKBotEntities db)
        {
            var chatId = update.@object.message.from_id;
            MessagesSendParams @params = new MessagesSendParams();
            var keyboardBuilder = new KeyboardBuilder().Clear();

            try
            {
                if (update.@object.message.text.Length > 0)
                {
                    var ids = new long[] { chatId };

                    var user = db.Users.Single(usr => usr.chatId == chatId);
                    user.tag = "Личный кабинет";
                    db.SaveChanges();

                    var report = db.Reports.Where(r=>r.chatId == chatId).Max();
                    report.comment = update.@object.message.text.Trim();
                    report.datetime = DateTime.Now;
                    report.state = 1;

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

                    @params.Keyboard = keyboardBuilder.Build();
                    @params.Message = "✅Отчет сохранён. Увидимся завтра!\n";
                    @params.UserId = chatId;
                    @params.RandomId = GetRandomId();
                    client.Messages.SendAsync(@params);
                }
                else
                {
                    @params.Message = "Не распознал сообщение 😕 Попробуйте, пожалуйста, ещё раз";
                    @params.UserId = chatId;
                    @params.RandomId = GetRandomId();
                    client.Messages.SendAsync(@params);
                }
            }
            catch (Exception ee)
            {
                @params.Message = "‼Ошибка в GetReportCommentCommand: " + 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();
        public int GetRandomId()
        {
            var intBytes = new byte[4];

            Rng.GetBytes(intBytes);

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