using Newtonsoft.Json;
using System;
using System.Diagnostics;
using System.IO;

namespace IOB_UT_NEXT
{
    public class FileProcMan
    {
        #region Public Constructors

        /// <summary>
        /// Init di base
        /// </summary>
        /// <param name="toolDir"></param>
        /// <param name="exeFileName"></param>
        public FileProcMan(string toolDir, string exeFileName)
        {
            this.confFileNameOut = "conf.json";
            this.baseDir = toolDir;
            this.exeName = exeFileName;
            appPath = Path.Combine(baseDir, exeName);
        }

        /// <summary>
        /// Init con chiave Redis (es Emmegi FPW)
        /// </summary>
        /// <param name="toolDir"></param>
        /// <param name="exeFileName"></param>
        /// <param name="redisKey"></param>
        /// <param name="refConfFileName"></param>
        public FileProcMan(string toolDir, string exeFileName, string redisKey, string refConfFileName)
        {
            this.confFileNameOut = "conf.json";
            this.redisKey = redisKey;
            this.baseDir = toolDir;
            this.exeName = exeFileName;
            appPath = Path.Combine(baseDir, exeName);
            // leggo file di conf base
            string refConfFile = Path.Combine(baseDir, refConfFileName);
            this.refConf = File.ReadAllText(refConfFile);
        }

        /// <summary>
        /// Init completa (es Fimat/Giacovelli)
        /// </summary>
        /// <param name="archiveDir"></param>
        /// <param name="convertDir"></param>
        /// <param name="toolDir"></param>
        /// <param name="exeFileName"></param>
        /// <param name="refConfFileName"></param>
        /// <param name="sheetName"></param>
        public FileProcMan(string archiveDir, string convertDir, string toolDir, string exeFileName, string refConfFileName, string sheetName)
        {
            this.archDir = archiveDir;
            this.convDir = convertDir;
            this.confFileNameOut = "conf.json";
            this.baseDir = toolDir;
            this.exeName = exeFileName;
            this.sheetName = sheetName;
            appPath = Path.Combine(baseDir, exeName);
            // leggo file di conf base
            string refConfFile = Path.Combine(baseDir, refConfFileName);
            this.refConf = File.ReadAllText(refConfFile);
        }

        #endregion Public Constructors

        #region Public Methods

        /// <summary>
        /// Processa il singolo file (tipo ricette Giacovelli) e riporta tempo esecuzione
        /// </summary>
        /// <returns></returns>
        public TimeSpan doProcess(string fPath, int idxODL)
        {
            TimeSpan outVal = new TimeSpan();
            Stopwatch sw = new Stopwatch();
            // preparo file conf
            createConfFile(fPath, idxODL);
            // avvio processing
            Console.WriteLine("calling ext app with args:");
            Console.WriteLine($"{appPath} {confFileNameOut}");
            Console.WriteLine();

            ProcessStartInfo psi = new ProcessStartInfo
            {
                FileName = appPath,
                Arguments = $"{confFileNameOut}",
                WindowStyle = ProcessWindowStyle.Minimized,
                //WindowStyle = ProcessWindowStyle.Hidden,
                UseShellExecute = false,
                //CreateNoWindow = true,
                RedirectStandardOutput = true,
                RedirectStandardInput = true,
            };

            sw.Start();

            Process p = Process.Start(psi);

            string q = "";
            while (!p.HasExited)
            {
                q += p.StandardOutput.ReadToEnd();
            }

            sw.Stop();
            outVal = sw.Elapsed;

            return outVal;
        }

        #endregion Public Methods

        #region Protected Fields

        protected string appPath = "";
        protected string archDir = "";
        protected string baseDir = "";
        protected string confFileNameOut = "";
        protected string convDir = "";
        protected string exeName = "";
        protected string refConf = "";
        protected string sheetName = "";
        protected string redisKey = "";

        #endregion Protected Fields

        #region Protected Methods

        protected string fixJsonDir(string origPath)
        {
            string answ = JsonConvert.ToString(origPath);
            answ = answ.Substring(1, answ.Length - 2);
            return answ;
        }

        #endregion Protected Methods

        #region Private Methods

        private void createConfFile(string item, int idxOdl)
        {
            string outFileName = Path.GetFileName(item).Replace("xlsx", "json");
            string rawContent = String.Copy(refConf);
            rawContent = rawContent.Replace("{{ArchiveDir}}", fixJsonDir(archDir));
            rawContent = rawContent.Replace("{{ConvertDir}}", fixJsonDir(convDir));
            rawContent = rawContent.Replace("{{FileInPath}}", fixJsonDir(item));
            rawContent = rawContent.Replace("{{FileOutPath}}", outFileName);
            rawContent = rawContent.Replace("{{TargetSheetName}}", sheetName);
            if (redisKey != null)
            {
                rawContent = rawContent.Replace("{{redisKey}}", redisKey);
            }
            rawContent = rawContent.Replace("987654321", $"{idxOdl}");
            // calcolo nome file conf specifico
            confFileNameOut = $"conf_{outFileName}";
            File.WriteAllText(confFileNameOut, rawContent);
        }

        #endregion Private Methods
    }
}