using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.IO;

namespace NewPosInstaller
{
    public class InstallerUpdate : Echo, IProcess
    {
        //private bool isStop = false;

        /// <summary>
        /// 설치프로그램 업데이트 
        /// </summary>
        /// <returns></returns>
        public bool Execute()
        {
            bool retValue = false; 
            try
            {
                base.OnEcho("POS Installer update");

                ComLog.WriteLog(ComLog.Level.trace
                              , System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Name + "."
                              + System.Reflection.MethodBase.GetCurrentMethod().Name + "()"
                              , "Start");

                string downFile = string.Empty; 
                string downPath = string.Empty;

                // 압출툴 존재여부 확인, 없으면 FTP 서버에서 다운로드 받는다.
                downFile = "7za.exe";
                downPath = Path.Combine(DirInfo.WorkDir, downFile);
                if (File.Exists(downPath) == false)
                {
                    base.OnEcho(string.Format("Downloading library file\n[{0}]", downFile));

                    retValue = FtpDownload(DirInfo.WorkDir, downFile);
                    if (retValue == false) return retValue;

                    FileInfo f0 = new FileInfo(downPath);
                    if (f0 == null) return retValue = false;
                    if (f0.Length == 0) return retValue = false;
                }
                else
                {
                    ComLog.WriteLog(ComLog.Level.trace
                                  , System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Name + "."
                                  + System.Reflection.MethodBase.GetCurrentMethod().Name + "()"
                                  , string.Format("  => FTP Download Result={0} File={1}", "Skip", downFile));
                }

                base.OnEcho(string.Format("Checking installer version\n[{0}]", downFile));

                // 버전정보 다운로드 
                //      (NewPosInstaller.ver => ini format file)
                //      [NewPosInstaller]
                //      ver=1.0.0.0
                downFile = "NewPosInstaller.ver";
                downPath = Path.Combine(DirInfo.WorkDir, downFile);
                retValue = FtpDownload(DirInfo.WorkDir, downFile);
                if (retValue == false) return false;
                if (File.Exists(downPath) == false) return retValue = false;
                FileInfo f1 = new FileInfo(downPath);
                if (f1 == null) return retValue = false;
                if (f1.Length == 0) return retValue = false; 


                // 버전 비교 
                string newVer = IniFile.GetValue(Path.Combine(DirInfo.WorkDir, downFile), "NewPosInstaller", "ver", "");
                if (string.IsNullOrWhiteSpace(newVer)) return false;
                if (BasicInfo.InstallPgmVer == newVer) return false;

                ComLog.WriteLog(ComLog.Level.trace
                              , System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Name + "."
                              + System.Reflection.MethodBase.GetCurrentMethod().Name + "()"
                              , string.Format("  => CurrentVer={0} NewVer={1}", BasicInfo.InstallPgmVer, newVer), true);

                base.OnEcho(string.Format("Updating installer program.\n[{0}]", downFile));


                // 업데이트 파일 다운로드 
                downFile = "NewPosInstaller.zip";
                downPath = Path.Combine(DirInfo.DownDir, downFile);
                retValue = FtpDownload(DirInfo.DownDir, downFile);
                if (retValue == false) return retValue;
                if (File.Exists(downPath) == false) return retValue = false;
                FileInfo f2 = new FileInfo(downPath);
                if (f2 == null) return retValue = false;
                if (f2.Length <= 0) return retValue = false; 


                // 다운파일 압축 해제 
                retValue = ComLib.ExcuteUnzip(DirInfo.WorkDir, Path.Combine(DirInfo.DownDir, downFile), DirInfo.WorkDir);

                ComLog.WriteLog(ComLog.Level.trace
                              , System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Name + "."
                              + System.Reflection.MethodBase.GetCurrentMethod().Name + "()"
                              , string.Format("  => Download file unzip Result={0} File={1}", retValue ? "Success" : "Failed", downFile), true);
                //if (retValue == false) return false;

                return retValue;
            }
            catch (Exception ex)
            {
                ComLog.WriteLog(ComLog.Level.Exception
                              , System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Name + "."
                              + System.Reflection.MethodBase.GetCurrentMethod().Name + "()"
                              , "  => Exception : " + ex.Message);
                return retValue = false;
            }
            finally
            {
                ComLog.WriteLog(ComLog.Level.trace
                              , System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Name + "."
                              + System.Reflection.MethodBase.GetCurrentMethod().Name + "()"
                              , string.Format("End"));
            }
        }

        public void Stop()
        {
            //this.isStop = true;
        }

        private bool FtpDownload(string downPath, string downFile)
        {
            bool retValue = false;
            try
            {
                string svrPath = ServerInfo.FtpPath + downFile;
                string locPath = Path.Combine(downPath, downFile);
                string errMsg = string.Empty; 
                ComLib.CreateDirectory(downPath);
                ComLib.FileDelete(locPath);

                FTP ftp = new FTP(ServerInfo.FtpIP, ServerInfo.FtpUser, ServerInfo.FtpPass);
                if (ftp == null) return false;

                retValue = ftp.Download(svrPath, locPath, ref errMsg);
                if (retValue == false)
                {
                    ComLog.WriteLog(ComLog.Level.Error
                                  , System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Name + "."
                                  + System.Reflection.MethodBase.GetCurrentMethod().Name + "()"
                                  , "  => FTP Download error " + errMsg);
                }

                return retValue;
            }
            catch (Exception ex)
            {
                ComLog.WriteLog(ComLog.Level.Exception
                              , System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Name + "."
                              + System.Reflection.MethodBase.GetCurrentMethod().Name + "()"
                              , "  => Exception : " + ex.Message);
                return false;
            }
            finally
            {
                ComLog.WriteLog(ComLog.Level.trace
                              , System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Name + "."
                              + System.Reflection.MethodBase.GetCurrentMethod().Name + "()"
                              , string.Format("  => FTP Download Result={0} File={1}{2}", retValue ? "Success" : "Failed", downPath, downFile), true);
                System.Threading.Thread.Sleep(100);
            }
        }
    }
}
