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

namespace SvetoforVKBot.Models.Dop
{
    public class GetData
    {
        public void updateUser(RootObject update, VkApi client, SvetoforVKBot.Data.SvetoforVKBotEntities db)
        {
            var chatId = update.@object.message.from_id;
            MessagesSendParams @params = new MessagesSendParams();

            try
            {
                var ids = new long[] { chatId };
                var user = client.Users.Get(ids);
                var lastName = user[0].LastName;
                var firstName = user[0].FirstName;


                var checkUser =  db.Users.FirstOrDefault(u => u.chatId == chatId);
                if(checkUser!=null)
                {
                    checkUser.firstName = firstName;
                    checkUser.lastName = lastName;
                }
                else
                {
                    db.Users.Add(new Data.Users()
                    {
                        chatId = chatId,
                        firstName = firstName,
                        lastName = lastName,
                        sourse = JsonConvert.SerializeObject(new Sourses()
                        {
                            sourses = new List<Sourse>() { new Sourse() { name = "main", dateTime = DateTime.Now } }
                        })
                    });
                }

                db.SaveChanges();
            }
            catch (Exception ee)
            {
                @params.Message = "‼Ошибка в GetData: " + 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);
        }
    }
}
