using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading;
using SmartZip.Logic;
using DataAccessLayer;
using System.Collections.ObjectModel;
using System.IO;
using AppConfigParser;

namespace GestoreTrimestrale.Logic
{
    public class ZipManagerProcess : IDisposable
    {
        public Thread workingThread { get; private set; }

        private static NLog.Logger logger = NLog.LogManager.GetCurrentClassLogger();

        private ZipConfiguration zipConfiguration = new ZipConfiguration();
        //number of process iterations
        public int Iterations { get; private set; }
        private int interval { get; set; } //interval to restarting zipping process
        private string logFile { get; set; } //in which zip process will be saving errors (I hope will be never used)

        private bool sleepDuringFirstRun = true;

        private SmartZip.Logic.ZipProcessSeparated process;

        //just setting up zipWorker, interval in minutes for repeating zip process
        public ZipManagerProcess(int interval, string logFile, bool sleepDuringFirstRun = true, ObservableCollection<ZipItem> zipPackages = null, string suffix = null, string suffixApp = null, string suffixNoApproval = null, bool approval = false, int scenarioID=0)
        {
            this.process = new SmartZip.Logic.ZipProcessSeparated(logFile, zipPackages, suffix, suffixApp, suffixNoApproval, approval, scenarioID);//create new instance of the process 
            this.sleepDuringFirstRun = sleepDuringFirstRun;
            this.interval = 1000 * 60 * interval; //Interval is in minutes if you're wondering
            this.logFile = logFile; // ConfigurationManager.AppSettings["logFile"];          
        }
        public ManagerProcessStatusEnum Status
        {
            get
            {
                if (workingThread == null || workingThread.ThreadState == ThreadState.Unstarted) return ManagerProcessStatusEnum.Pending;
                if (workingThread.ThreadState == ThreadState.Running || workingThread.ThreadState == ThreadState.WaitSleepJoin) return ManagerProcessStatusEnum.Processing;
                return ManagerProcessStatusEnum.Completed;
            }
        } //process status        
        public int Start(XmlConfigurationParser parser, string path)
        {
         
            this.workingThread = constructWorkingThread(process, parser, path);
            if (this.workingThread == null) return -1;
            if (this.workingThread.ThreadState != ThreadState.Unstarted && this.workingThread.ThreadState != ThreadState.Stopped) return -2;
            this.workingThread.Start();
            return 1;
        }

        private Thread constructWorkingThread(ZipProcessSeparated process,XmlConfigurationParser parser, string path)
        {
            Thread t = new Thread(() =>
            {

                string fileID = ConfigurationManager.AppSettings["approvalFileId"];
                bool isLotto1 = bool.Parse(ConfigurationManager.AppSettings["isFirstLotto"]);
                int idfkZip = -1;
                string zztop = "-1";
                string idfkZip_s = "";

                if (fileID != "")
                {
                    using (DataAccessDE de = new DataAccessDE(DBProvider.SqlServerStampeC6))
                    {
                        string s = "select FKIDElaborazioneZIP from c6martperiodico.gestione_zip_ftp where id = " + fileID;
                        zztop = de.ExecuteScalar(DBProvider.SqlServerStampeC6, CommandType.Text, "select FKIDElaborazioneZIP from c6martperiodico.gestione_zip_ftp where id = " + fileID).ToString();
                    }

                    //string idfkZip_s = ConfigurationManager.AppSettings["idFKZip"];

                    if (int.TryParse(zztop, out idfkZip))
                    {
                        idfkZip_s = idfkZip.ToString();
                    }
                //    else
                 //   {
                  //      idfkZip_s = ZipProcessSeparated.InizioElaborazioneZip();
                   // }
                }
             

                int isLotto1Int = (isLotto1) ? 1 : 0;
                string z = ConfigurationManager.AppSettings["WasApprovalFileSent"].ToString();
                bool ttest;
                bool wasIDFIleSend = false;
                if (bool.TryParse(z, out ttest))
                    wasIDFIleSend = ttest;
                else
                    wasIDFIleSend = (z == "1");

                //bool.Parse(ConfigurationManager.AppSettings["WasApprovalFileSent"]);
               
                process.ProcessZip(false, idfkZip_s, fileID,  interval, false, wasIDFIleSend, isLotto1Int);
                //if (process.isPdfProcessFinished())
                //{
                //    string folder = process.OutputZipFolder;
                //    foreach (string f in Directory.GetFiles(folder))
                //    {
                //        if (f.Contains(".7z"))
                //        {
                //            string message;
                //            IDXVerificator v = new IDXVerificator();
                //            int res = v.Execute(f, true, out message);
                //            if (res < 0)
                //                logger.Error(message);
                //            else
                //                logger.Debug("file {0} is correct", f);
                //        }
                //    }
                //}

                parser.SaveTo(path);                
            });
            return t;
        }

        //we will check if it's ok to restart zip process
      
        public void Dispose()
        {
            if (workingThread != null)
            {
                if (workingThread.IsAlive)
                {
                    workingThread.Abort();
                }
                workingThread = null;
            }
        }
    }
}