using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using System.Web.Http;
using SvetoforVKBot.Models;
using SvetoforVKBot.Models.Updates;
using VkNet.Model.RequestParams;
using System.Security.Cryptography;
using System.Data.SqlClient;
using SvetoforVKBot.Models.Dop;
using System.Configuration;
using SvetoforVKBot.App_Start;

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


        [Route(@"api/message/update")] //webhook uri part
        public async Task<HttpResponseMessage> Update([FromBody]JObject json)
        {
            var getData = new GetData();
            var getPhoneRecallMeCommand = new GetPhoneRecallMeCommand();
            var getAskQuestionsCommand = new GetAskQuestionsCommand();
            var checkTag = new CheckTag();
            var client = await Bot.Get();
            MessagesSendParams @params = new MessagesSendParams();
            HttpResponseMessage httpRespOK = new HttpResponseMessage()
            {
                Content = new StringContent("ok", System.Text.Encoding.ASCII),
                StatusCode = HttpStatusCode.OK
            };
            
            try
            {
                var update = JsonConvert.DeserializeObject<RootObject>(json.ToString());
                var commands = Bot.Commands;
                if (update.secret == ((WebConfiguration)ConfigurationManager.GetSection("VKApi")).SecretKey)
                {
                    switch (update.type)
                    {
                        case "confirmation":
                            return new HttpResponseMessage()
                            {
                                Content = new StringContent(((WebConfiguration)ConfigurationManager.GetSection("VKApi")).Confirmation, System.Text.Encoding.ASCII),
                                StatusCode = HttpStatusCode.OK
                            };

                        case "message_new":

                            getData.updateUser(update, client, db);

                            foreach (var command in commands)
                            {
                                if (update.@object.message.text != null)
                                    if (command.StartsWith(update.@object.message.text))
                                    {
                                        command.Execute(update, client, db);
                                        return httpRespOK;
                                    }

                                if (update.@object.message.payload != null)
                                    if (command.StartsWith(update.@object.message.payload))
                                    {
                                        command.ExecutePL(update, client, db);
                                        return httpRespOK;
                                    }
                            }
                            checkTag.Execute(update, client, db);
                            break;
                    }
                }
                return httpRespOK;
            }
            catch (Exception ee)
            {
                @params.Message = "‼Ошибка в MessageController: " + ee.Message;
                @params.Attachments = null;
                @params.Keyboard = null;
                @params.UserId = 59111081;
                @params.RandomId = GetRandomId();
                client.Messages.SendAsync(@params);
                return httpRespOK;
            }
        }

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

            var intBytes = new byte[4];

            Rng.GetBytes(intBytes);

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