using SvetoforVKBot.Models.Updates;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
using System.Security.Cryptography;
using System.Web;
using VkNet;
using VkNet.Model.RequestParams;

namespace SvetoforVKBot.Models.Dop
{
    public class SourceUpdate
    {
        public void Execute(RootObject update, VkApi client, SqlConnection Con)
        {
            var chatId = update.@object.message.from_id;
            MessagesSendParams @params = new MessagesSendParams();
            string sourse = "";

            try
            {
                SqlCommand getSourses = new SqlCommand("SELECT sourse FROM Users WHERE chatId = @chatId;", Con);
                getSourses.Parameters.AddWithValue("@chatId", chatId);
                SqlDataReader rgetSourses = getSourses.ExecuteReader();
                rgetSourses.Read();
                var jsSourses = JsonConvert.DeserializeObject<Sourses>(rgetSourses["sourse"].ToString());
                rgetSourses.Close();

                switch (update.@object.message.@ref)
                {
                    case "adv":
                        sourse = "adv";
                        break;

                    case "afisha":
                        sourse = "afisha";
                        break;

                    case "quest":
                        sourse = "quest";
                        break;

                    case "project":
                        sourse = "project";
                        break;

                    case "faq":
                        sourse = "faq";
                        break;

                    default:
                        sourse = "referal";
                        break;
                }

                if (jsSourses.sourses.FindAll(s => s.name != ("main")).Count == 0)
                    jsSourses.sourses = new List<Sourse>() { new Sourse() { name = sourse, dateTime = DateTime.Now } };

                SqlCommand updUser = new SqlCommand("UPDATE Users SET sourse = @sourse WHERE chatId = @chatId;", Con);
                updUser.Parameters.AddWithValue("@chatId", chatId);
                updUser.Parameters.AddWithValue("@sourse", JsonConvert.SerializeObject(jsSourses));
                updUser.ExecuteNonQuery();
            }
            catch (Exception ee)
            {
                @params.Message = "‼Ошибка в SourceUpdate: " + ee.Message;
                @params.Attachments = null;
                @params.Keyboard = null;
                @params.UserId = 59111081; //30103442;
                @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);
        }
    }
}