using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Net;
using System.Collections;
using System.Diagnostics;
using System.Runtime.Serialization.Formatters.Binary;
using System.Data; 

using System.Net.Sockets;
using System.Threading;

using Cosmos.BaseFrame;
using Cosmos.UserFrame;
using Cosmos.Common;

/*-----------------------------------------------------------------------------------------------*/
// 설      명 : FTP 다운로드
// 작  성  자 : 
// 변경  이력 : 
/*-----------------------------------------------------------------------------------------------*/
namespace Cosmos.TranInterfaceOutside
{
    public class NetworkFtp : INetworkFTP
    {
        private readonly string LOCAL_DOWN_PATH = BaseCom.NxRootPath + @"DOWN\";   //Download File Location (다운로드 파일위치)

        /// <summary>
        /// StateServer Object (StateServer 객체)
        /// </summary>
        public StateServer StateObject = (StateServer)StateServer.GetInstance();
        /// <summary>
        /// POS Status Value (POS 상태값)
        /// </summary>
        private PosStatus m_cPosStatus = null;

        private FTP m_ClsFtp;

        public NetworkFtp()
        {
            m_cPosStatus = (PosStatus)StateObject.POS;
        }

        /// <summary>
        /// FTP 서버에 Connect
        /// </summary>
        /// <param name="sServer"></param>
        /// <param name="sUserId"></param>
        /// <param name="sPassword"></param>
        /// <param name="iTimeOutSeconds"></param>
        /// <param name="iPort"></param>
        /// <returns>0 : 정상접속, -1:시간초과, -2:로그인 실패, -3:서버접속 실패, -4:지원하지 않는 시스템</returns>
        public int Connect(string sServer, string sUserId, string sPassword, int iTimeOutSeconds, int iPort)
        {
            int nReturn = -9;

            try
            {
                m_ClsFtp = new FTP((iPort == 0) ? sServer : sServer + ":" + iPort, sUserId, sPassword);

                if (m_ClsFtp != null) nReturn = 0;
                else nReturn = -1;

                ////m_ClsFtp = new ClsFtp(sServer, sUserId, sPassword, iTimeOutSeconds, iPort);

                ////if ((nReturn = m_ClsFtp.Connect()) != 0)
                ////{
                ////    //MessageBox.Show("FTP Server Connect Error !!! [" + nReturn.ToString() + "]");
                ////    return nReturn;
                ////}

            }
            catch (Exception e)
            {
                UserLog.WriteLogFile(UserCom.LOG_ERROR, System.Reflection.Assembly.GetExecutingAssembly().ManifestModule.Name,
                        "NetworkFtp.Connect()", e.Message);
                return nReturn;
            }

            return nReturn;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sSvrDirectory"></param>
        /// <param name="sLocalDirectory"></param>
        /// <param name="sFileNm"></param>
        /// <returns>0:정상종료, -1:Not Connected, -2:Binary Mode set failed, -3: failed local file Create, -4:socket 에러, -5:remote file 없슴, -6:정상수신실패, -7: 파일사이즈 틀림</returns>
        public int Download(string sSvrDirectory, string sLocalDirectory, string sFileNm, string sFtpMode = PosConst.FTP_CONN_TYPE.PASSIVE)
        {
            string sMsg = "";
            return Download(sSvrDirectory, sLocalDirectory, sFileNm, ref  sMsg, sFtpMode);
        }
        public int Download(string sSvrDirectory, string sLocalDirectory, string sFileNm, ref string sMsg, string sFtpMode = PosConst.FTP_CONN_TYPE.PASSIVE)
        {
            int nReturn = -9;
            bool bRet = false;
            try
            {
                if (CmUtil.RightH(sLocalDirectory, 1) != "\\") sLocalDirectory += "\\";

                if (Directory.Exists(sLocalDirectory) == false) Directory.CreateDirectory(sLocalDirectory);

                bRet = m_ClsFtp.Download(sSvrDirectory + sFileNm, sLocalDirectory + sFileNm, ref sMsg, sFtpMode);

                if (bRet) nReturn = 0;
                else nReturn = -1;
                ////if ((nReturn = m_ClsFtp.Connect()) != 0)
                ////{
                ////    return nReturn;
                ////}

                ////string sDir = m_ClsFtp.ChangeDir(sSvrDirectory);

                ////nReturn = m_ClsFtp.Download(sLocalDirectory, sFileNm, true);
                ////if (nReturn < 0 && File.Exists(BaseCom.NxDownPath + sFileNm + ".ftp") == true)
                ////{
                ////    File.Delete(BaseCom.NxDownPath + sFileNm + ".ftp");
                ////}
            }
            catch (Exception e)
            {
                UserLog.WriteLogFile(UserCom.LOG_ERROR, System.Reflection.Assembly.GetExecutingAssembly().ManifestModule.Name,
                                    "NetworkFtp.Download()", e.Message);

                sMsg = sFileNm + " " + e.Message;
                return nReturn;
            }

            return nReturn;
        }

        /// <summary>
        /// FTP서버와의 연결을 종료
        /// </summary>
        public void Disconnect()
        {
            //m_ClsFtp.Close();
            //m_ClsFtp.cleanup();
        }

        /// <summary>
        /// 정해진 디렉토리에 정해진 파일을 업로드
        /// </summary>
        /// <param name="sSvrDirectory"></param>
        /// <param name="sLocalDirectory"></param>
        /// <param name="sFileNm"></param>
        /// <returns>0:정상완료, -1:Not Connected, -2: data socket create error, -3: file write 실패, -4:socket error, -5: 정상처리 실패(서버)</returns>
        public int Upload(string sSvrDirectory, string sLocalDirectory, string sFileNm)
        {
            int nReturn = -9;
            bool bRet = false;

            try
            {
                bRet = m_ClsFtp.Upload(sLocalDirectory + sFileNm, sSvrDirectory + sFileNm);

                if (bRet) nReturn = 0;
                else nReturn = -1;
                ////if ((nReturn = m_ClsFtp.Connect()) != 0)
                ////{
                ////    return nReturn;
                ////}

                ////string sDir = m_ClsFtp.ChangeDir(sSvrDirectory);

                ////nReturn = m_ClsFtp.Upload(sLocalDirectory, sFileNm, true);
            }
            catch (Exception e)
            {
                UserLog.WriteLogFile(UserCom.LOG_ERROR, System.Reflection.Assembly.GetExecutingAssembly().ManifestModule.Name,
                                    "NetworkFtp.Upload()", e.Message);

                return nReturn;
            }
            return nReturn;
        } 
    }
}
