using DataBaseBackups.MindrocketsInc.Helpers;
using MindRocketsInc.Optimizer.Logic;
using MindRocketsInc.Optimizer.Logic.Storage;
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.IO.Compression;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace ReturnReports
{
    internal class Program
    {
        private static void InitEncryption()
        {
            var iv = Mindrockets.Helpers.Config.Instance.GetValueFromConfig("memtracw", "");
            var key = Mindrockets.Helpers.Config.Instance.GetValueFromConfig("memheap", "");

            EncryptionHelper.Initialize(key, iv);
            EncapsulatedEncryption.Init((r) => EncryptionHelper.Encrypt(r), (r) => EncryptionHelper.Decrypt(r));



        }
        static void Main(string[] args)
        {
            if (args.Length == 0)
            {
                Console.WriteLine("Please specify mode: aih or sl");
                return;
            }
            string mode = args[0].ToLower();

            //  InitEncryption();
            var storageManager = StorageManagerFactory.CreateInstance("s3");

            if (mode == "aih")
            {
                RunAihProcessing(storageManager);
            }
            else
            {
                Console.WriteLine("Unknown mode. Use: aih or signs");
            }

           

        }
        static void RunAihProcessing(IStorageManager storageManager)
        {
            var data = storageManager.ExploreDirectory("backup/instant")
                .Where(p => p.Contains("VMI1025388") && p.Contains(".zip"))
                .Select(p => string.Join("/", p.Split('/').Skip(1)))
                .ToList();

            var output = "outputData";
            var jsonOutputDir = Path.Combine(output, "jsons");
            Directory.CreateDirectory(output);
            Directory.CreateDirectory(jsonOutputDir);

            foreach (var item in data)
            {
                try
                {
                    var filename = Path.GetFileName(item);
                    var outputfile = Path.Combine(output, filename);
                    var outputDataFile = Path.Combine(jsonOutputDir, Path.GetFileName(Path.ChangeExtension(outputfile, ".json")));
                    var FileNameWithoutEx = Path.GetFileNameWithoutExtension(filename);
                    var dirName = Path.Combine(output, FileNameWithoutEx);

                    if (File.Exists(outputfile) && File.Exists(outputDataFile))
                    {
                        Mindrockets.Helpers.Logger.Instance.Info($"{outputDataFile} was found --skip");
                        continue;
                    }

                    File.Delete(outputfile);
                    Directory.Delete(dirName, true);

                    var bytes = storageManager.DownloadFile(item);
                    File.WriteAllBytes(outputfile, bytes);
                    Directory.CreateDirectory(dirName);
                    ZipFile.ExtractToDirectory(outputfile, dirName);

                    var requiredFile = Path.Combine(dirName, "PostgresDbs", "localhost_AihDb.bak");
                    if (!File.Exists(requiredFile)) continue;

                    var processor = new PostgresBackupProcessor();
                    var date = string.Join("-", FileNameWithoutEx.Split('_').Reverse());
                    var query = $"select sum(br.\"Count\") \"Usage\",c.\"Counter\" ,c.\"Name\"  ,br.\"btnId\" ,br.\"BtnIndex\"  ,br.\"clientId\" ,bi.\"DisplayName\" \"Feature\" ,b.\"DisplayName\" \"Category\",'{date}' \"CaptureDate\"  from \"buttonReport\" br inner join \"ButtonIndexs\" bi on br.\"btnId\" =bi.\"BtnId\" and br.\"BtnIndex\" =bi.\"BtnIndex\" inner join \"Buttons\" b on bi.\"BtnId\" =b.\"Id\" inner join \"Clients\" c on br.\"clientId\" =c.\"Id\"  group by br.\"btnId\" ,br.\"BtnIndex\"  ,br.\"clientId\",c.\"Name\"  ,bi.\"DisplayName\",b.\"DisplayName\",c.\"Counter\";";

                    DataTable reqData = null;
                    try
                    {
                        reqData = processor.ProcessBackup(requiredFile, query);
                    }
                    catch
                    {
                        Thread.Sleep(5000);
                        try { reqData = processor.ProcessBackup(requiredFile, query); } catch (Exception ex) { Mindrockets.Helpers.Logger.Instance.Error(ex); continue; }
                    }

                    if (reqData != null)
                    {
                        File.WriteAllText(outputDataFile, Newtonsoft.Json.JsonConvert.SerializeObject(reqData));
                    }
                }
                catch (Exception ex)
                {
                    Mindrockets.Helpers.Logger.Instance.Error(ex);
                }
            }
        }

    }
}
