using SvetoforVKBot.Models;
using SvetoforVKBot.Models.Updates;
using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.IO;
using System.Threading;
using System.Web.Mvc;
using VkNet;
using VkNet.Enums.SafetyEnums;
using VkNet.Model.Keyboard;
using VkNet.Model.RequestParams;
using VkNet.Model;
using System.Security.Cryptography;
using Newtonsoft.Json;
using VkNet.Model.Attachments;
using System.Linq;
using Google.Apis.Auth.OAuth2;
using Google.Apis.Services;
using Google.Apis.Sheets.v4;
using Google.Apis.Sheets.v4.Data;
using SvetoforVKBot.App_Start;
using System.Configuration;
using SvetoforVKBot.Data;

namespace SvetoforVKBot.Controllers
{
    class GoogleApi : IDisposable
    {
        readonly string[] Scopes = { SheetsService.Scope.Spreadsheets };
        readonly string ApplicationName = "chatbot-vk-instagram";
        
        //readonly string sheet = "Лист1";
        readonly string credential_file = "client_secret.json";
        SheetsService service;

        public GoogleApi()
        {
            try
            {
                GoogleCredential credential;
                string filePath = System.Web.HttpContext.Current.Request.PhysicalApplicationPath + @"\" + credential_file;
                using (var stream = new FileStream(filePath, FileMode.Open, FileAccess.Read)) //new FileStream(credential_file, FileMode.Open, FileAccess.Read))
                {
                    credential = GoogleCredential.FromStream(stream)
                        .CreateScoped(Scopes);
                }
                // Create Google Sheets API service.
                service = new SheetsService(new BaseClientService.Initializer()
                {
                    HttpClientInitializer = credential,
                    ApplicationName = ApplicationName,
                });
            }
            catch (Exception ee)
            {
                Console.WriteLine("Ошибка при работе с google sheets: {0}", ee.Message);
            }
        }
        public void AppendEntry(string range, List<IList<object>> rangesValues, string sheet)
        {
            var valueRange = new ValueRange();
            valueRange.Values = rangesValues;
            var appendRequest = service.Spreadsheets.Values.Append(valueRange, sheet, range);
            appendRequest.ValueInputOption = SpreadsheetsResource.ValuesResource.AppendRequest.ValueInputOptionEnum.USERENTERED;
            var appendReponse = appendRequest.Execute();
        }

        public void Dispose()
        {
            ;
        }
        
    }

    public class ExportDataController : Controller
    {
        readonly string SheetAllUsersId = "1jr68NfIrlz2bVsN-HZg0Kv2sSJ82J5G-EbtXl-YMK44";
        readonly string SheetConsultationsId = "1nWHvWufxDy6g2ZJtqd4K8MDM6Gh8OHWasRGXIyqbT2k";

        private SvetoforVKBot.Data.SvetoforVKBotEntities db = new SvetoforVKBot.Data.SvetoforVKBotEntities();
        protected override void Dispose(bool disposing)
        {
            db.Dispose();
            base.Dispose(disposing);
        }
        private const int SELFCHATID = 59111081;
        //GET: AllUsers
        public HttpStatusCodeResult AllUsers()
        {
            List<ChatId> ids = new List<ChatId>();
            MessagesSendParams @params = new MessagesSendParams();
            MessagesSendParams @params2 = new MessagesSendParams();
            MessageEditParams editParams = new MessageEditParams();
            HttpStatusCodeResult httpResult = new HttpStatusCodeResult(200);

            var client = new VkApi();
            List<string> phones;
            string agree;
            string reg;
            var phone = "";
            try
            {
                client.AuthorizeAsync(new ApiAuthParams
                {
                    AccessToken = ((WebConfiguration)ConfigurationManager.GetSection("VKApi")).Token
                });

                #region Добавление в гугл таблицу

                using (GoogleApi myApi = new GoogleApi())
                {
                    List<IList<object>> rangeObj = new List<IList<object>>();

                    var users = db.Users.Where(usr => usr.export == 0).ToList();

                    foreach (var u in users)
                    {
                        phones = JsonConvert.DeserializeObject<List<string>>(u.phone);
                        if (phones.Count > 0)
                            phone = phones[0];
                        else
                            phone = "-";

                        if (u.reg == 1)
                            reg = "Зарегистрирован";
                        else
                            reg = "Не зарегистрирован";

                        if (u.agree == 1)
                            agree = "Есть";
                        else
                            agree = "Нет";

                        rangeObj.Add(new List<object>()
                            {
                                u.chatId.ToString(),
                                u.firstName.ToString(),
                                u.lastName.ToString(),
                                u.fio.ToString(),
                                reg,
                                phone,
                                u.birthday.ToShortDateString(),
                                agree,
                            });

                        var con = db.Users.Where(el => el.chatId == u.chatId).Single<Users>();
                        con.export = 1;
                        db.SaveChanges();

                        Thread.Sleep(30);
                    }

                    //Добавление в таблицу данных объектов
                    myApi.AppendEntry($"Лист1!A:H", rangeObj, SheetAllUsersId);
                }
                #endregion Добавление в гугл таблицу
            }
            catch (Exception ee)
            {
                @params.Message = "‼Ошибка в ExportDataController: " + ee.Message;
                @params.Attachments = null;
                @params.Keyboard = null;
                @params.UserId = 59111081;
                @params.RandomId = GetRandomId();
                client.Messages.SendAsync(@params);
            }

            return httpResult;
        }

        public HttpStatusCodeResult PersonalConsultations()
        {
            List<ChatId> ids = new List<ChatId>();
            MessagesSendParams @params = new MessagesSendParams();
            MessagesSendParams @params2 = new MessagesSendParams();
            MessageEditParams editParams = new MessageEditParams();
            HttpStatusCodeResult httpResult = new HttpStatusCodeResult(200);

            var client = new VkApi();
            List<string> phones;
            string phone = "";
            string birthdate = "";
            string date = "";
            try
            {
                client.AuthorizeAsync(new ApiAuthParams
                {
                    AccessToken = ((WebConfiguration)ConfigurationManager.GetSection("VKApi")).Token
                });

                #region Добавление в гугл таблицу

                using (GoogleApi myApi = new GoogleApi())
                {
                    List<IList<object>> rangeObj = new List<IList<object>>();

                    var consultations = db.PersonalConsultations.Join(db.Users, pc => pc.chatId, u => u.chatId, (pc, u) =>
                        new PersonalCons{ 
                        chatId = pc.chatId,
                        fio = u.fio,
                        phone = u.phone,
                        birthdate = u.birthday,
                        question = u.question,
                        date = pc.datetime,
                        state = pc.state
                        })
                        .Where(c => c.state == 1)
                        .ToList();

                    foreach (var c in consultations)
                    {
                        phones = JsonConvert.DeserializeObject<List<string>>(c.phone);
                        if (phones.Count > 0)
                            phone = phones[0];
                        else
                            phone = "-";

                        birthdate = c.birthdate.ToShortDateString();
                        date = c.date.ToString("dd.MM.yyyy HH:mm");

                        rangeObj.Add(new List<object>()
                            {
                                c.chatId,
                                c.fio,
                                phone,
                                birthdate,
                                c.question,
                                date,
                            });

                        var con = db.PersonalConsultations.Where(el => el.chatId == c.chatId).Single<PersonalConsultation>();
                        con.state = 2;
                        db.SaveChanges();

                        Thread.Sleep(30);
                    }

                    //Добавление в таблицу данных объектов
                    myApi.AppendEntry($"Лист1!A:H", rangeObj, SheetConsultationsId);
                }
                #endregion Добавление в гугл таблицу
            }
            catch (Exception ee)
            {
                @params.Message = "‼Ошибка в ExportDataController: " + ee.Message;
                @params.Attachments = null;
                @params.Keyboard = null;
                @params.UserId = 59111081;
                @params.RandomId = GetRandomId();
                client.Messages.SendAsync(@params);
            }

            return httpResult;
        }

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

            var intBytes = new byte[4];

            Rng.GetBytes(intBytes);

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