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

namespace NewPosInstaller
{
    /// <summary>
    /// POS 이미지 전체 다운로드 
    ///     07 POS운영이미지     PosConst.PGM_UPDATE_TYPE.CONTENTS
    ///     03 고객화면이미지    PosConst.PGM_UPDATE_TYPE.CUSTOMER
    ///     04 상품이미지        PosConst.PGM_UPDATE_TYPE.ITEM_IMAGE
    ///     05 캠페인이미지      PosConst.PGM_UPDATE_TYPE.CAMPAIGN
    ///     06 연습모드이미지    PosConst.PGM_UPDATE_TYPE.TEST_MODE
    /// </summary>
    public class PosImageDownload : Echo, IProcess
    {
        //private bool isStop = false; 

        public bool Execute()
        {
            bool retValue = false;

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


                if (string.IsNullOrWhiteSpace(BasicInfo.IMGDownDate) == false)
                {
                    base.OnEcho("POS operation image download skip.");
                    System.Threading.Thread.Sleep(1000);

                    ComLog.WriteLog(ComLog.Level.trace
                                  , System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Name + "."
                                  + System.Reflection.MethodBase.GetCurrentMethod().Name + "()"
                                  , string.Format("  => POS operation image download. Result={0} DownDate={1} ", "Skip", BasicInfo.IMGDownDate));

                    return retValue = true;
                }


                // 다운로드 정보 조회(IRT) 정보 획득 
                CmMessage cmCommPort = CmMessage.MakeMessageFromFile(Path.Combine(DirInfo.InstallDir, @"INI\CommPort.INI"));
                var commPort = ComLib.IntParse(ComLib.GetConfigInfo(cmCommPort, "SERVER", "SysInfoPort", ""));
                var commAddr = ServerInfo.SvrIP;
                ComLog.WriteLog(ComLog.Level.trace
                              , System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Name + "."
                              + System.Reflection.MethodBase.GetCurrentMethod().Name + "()"
                              , string.Format("  => Inquery infomration. ip={0} port={1}", commAddr, commPort.ToString()), true);

                bool isSuccess = true; 

                // 다운로드 이미지 목록 
                Dictionary<string, string> imgDownList = new Dictionary<string, string>();
                imgDownList.Add(PosConst.PGM_UPDATE_TYPE.CONTENTS, "POS Contents image");
                imgDownList.Add(PosConst.PGM_UPDATE_TYPE.CUSTOMER, "POS Customer display image");
                imgDownList.Add(PosConst.PGM_UPDATE_TYPE.ITEM_IMAGE, "POS Item image");
                imgDownList.Add(PosConst.PGM_UPDATE_TYPE.CAMPAIGN, "POS Campaign image");
                imgDownList.Add(PosConst.PGM_UPDATE_TYPE.TEST_MODE, "POS Testmode image");

                foreach (var lst in imgDownList)
                {
                    for (var i = 0; i < 3; i++)
                    {
                        retValue = ImageDownload(lst.Key, lst.Value, commAddr, commPort);
                        if (retValue == false)
                        {
                            isSuccess = false;
                        }
                        else
                        {
                            break;
                        }

                        System.Threading.Thread.Sleep(1000);
                    }
                }
                if (isSuccess)
                {
                    BasicInfo.IMGDownDate = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                    retValue = true;
                }

                return retValue = isSuccess;
            }
            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, Result={0}", retValue ? "Success" : "Failed"));
            }
        }

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

        private bool ImageDownload(string downKind, string downName, string commIp, int commPort)
        {
            bool retValue = false;

            try
            {
                ComLib.CreateDirectory(DirInfo.DownDir);
                ComLib.DeleteDirectoryInFile(DirInfo.TempDir, 2);

                #region ### POS 파일 전송 요청 IRT FTP IP/PORT/PW/FilePath 획득

                base.OnEcho(string.Format("Inquery ftp server information.\n{0}", downName));

                // 통신해더 생성
                string commHead = ItemColumn.MakeCommHeader(0, "06");

                Hashtable htSendData = new Hashtable();
                Hashtable htRecvData = new Hashtable();

                htSendData.Add(Column.IQ_PGMUPDATE_REQ.DATA.INQ_TYPE, Column.IQ_PGMUPDATE_REQ.MSG_ID);
                htSendData.Add(Column.IQ_PGMUPDATE_REQ.DATA.FILE_KIND, downKind);
                htSendData.Add(Column.IQ_PGMUPDATE_REQ.DATA.FILE_APP_TY, "0");
                htSendData.Add(Column.IQ_PGMUPDATE_REQ.DATA.FILE_YMDHMS, DateTime.Now.ToString("yyyyMMddHHmmss"));
                //htSendData.Add(Column.IQ_PGMUPDATE_REQ.DATA.DOWN_DIV, "U");
                htSendData.Add(Column.IQ_PGMUPDATE_REQ.DATA.DOWN_DIV, "A");

                NetworkJSON irt = new NetworkJSON();
                int ret = irt.IRTSendReceive(commIp, commPort, 1000 * 20, commHead, htSendData, ref htRecvData);
                if (ret != ComLib.OK)
                {
                    ComLog.WriteLog(ComLog.Level.Error
                                  , System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Name + "."
                                  + System.Reflection.MethodBase.GetCurrentMethod().Name + "()"
                                  , "  => Server communication error");
                    return false; 
                }
                string res = htRecvData[Column.IQ_INSTALL_STATUS_INQ.DATA.RES_CD].ToString();
                ComLog.WriteLog(res != "00" ? ComLog.Level.Error : ComLog.Level.trace
                              , System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Name + "."
                              + System.Reflection.MethodBase.GetCurrentMethod().Name + "()"
                              , string.Format("  => Inquery image download infomation, RespCode={0}, Result={1}", res, res == "00" ? "Success" : "Failed"));
                if (res != "00")
                {
                    return retValue = false; 
                }
                
                #endregion

                #region ### 이미지파일 다운로드 

                base.OnEcho(string.Format("{0} downloading.", downName));

                var ftpHost = htRecvData[Column.IQ_PGMUPDATE_RSP.DATA.FTP_IP].ToString();
                var ftpPort = ComLib.IntParse(htRecvData[Column.IQ_PGMUPDATE_RSP.DATA.FTP_PORT].ToString());
                var ftpUser = htRecvData[Column.IQ_PGMUPDATE_RSP.DATA.FTP_ID].ToString();
                var ftpPass = htRecvData[Column.IQ_PGMUPDATE_RSP.DATA.FTP_PWD].ToString();
                var downList = htRecvData[Column.IQ_PGMUPDATE_RSP.DATA.VALUE].ToString().Split(new string[] { "#~" }, StringSplitOptions.None);
                var value = downList[0].Split('|');
                var fileName = value[4].Trim();
                var svrPath = value[3].Trim();
                var locFile = Path.Combine(DirInfo.DownDir, fileName);
                ComLib.FileDelete(locFile);

                if (ftpPort == 0) ftpHost = string.Format("{0}:{1}", ftpHost, ftpPort.ToString());

                FTP ftp = new FTP(ftpHost, ftpUser, ftpPass);
                if (ftp == null) return false;

                if (svrPath.Substring(svrPath.Length - 1, 1) != "/") svrPath += "/";

                retValue = ftp.Download(svrPath + fileName, locFile);
                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", svrPath, fileName));

                System.Threading.Thread.Sleep(300);
                #endregion

                #region ### 이미지 파일 적용 (압축해지, 파일복사)

                base.OnEcho(string.Format("Donwload image file copy.\n{0}", downName));

                // 이미지 파일 적용 (압축해지, 파일복사)
                retValue = ComLib.ExcuteUnzip(DirInfo.WorkDir, locFile, DirInfo.TempDir, System.Diagnostics.ProcessWindowStyle.Hidden);
                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", locFile));
                if (retValue == false) return retValue;
                System.Threading.Thread.Sleep(300);

                ComLib.CreateDirectory(DirInfo.InstallDir);
                //DirectoryInfo[] dir = new DirectoryInfo(DirInfo.TempDir).GetDirectories();
                //foreach (DirectoryInfo d in dir)
                //{
                //    retValue = ComLib.DirectoryCopy(d.FullName, DirInfo.InstallDir, "");
                //    ComLog.WriteLog(ComLog.Level.trace
                //                  , System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Name + "."
                //                  + System.Reflection.MethodBase.GetCurrentMethod().Name + "()"
                //                  , string.Format("  => Download file copy Result={0} DestDirctory={1}", retValue ? "Success" : "Failed", DirInfo.InstallDir));
                //    if (retValue == false) return retValue;
                //} 
                retValue = ComLib.DirectoryCopy(DirInfo.TempDir, DirInfo.InstallDir, "");
                ComLog.WriteLog(ComLog.Level.trace
                              , System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Name + "."
                              + System.Reflection.MethodBase.GetCurrentMethod().Name + "()"
                              , string.Format("  => Download file copy Result={0} DestDirctory={1}", retValue ? "Success" : "Failed", DirInfo.InstallDir));
                if (retValue == false) return retValue;

                #endregion

                return retValue = true;
            }
            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("  => {0}/{1} download result={2}", downKind, downName, retValue ? "Success" : "Failed"), true);
            }
        }
    }
}
