using System;
using System.IO;
using EnterpriseDT.Net.Ftp;
using System.Text;
using System.Collections.Generic;
using System.Net;

namespace ChuPiao.Common.Core.Ftp
{
    public class FtpClient
    {
        private string _host;
        private string _remotePath;
        private string _userId;
        private string _password;
        private string _uri;
        public FtpClient(string host, string remotePath, string userId, string password)
        {
            _host = host;
            _remotePath = remotePath;
            _userId = userId;
            _password = password;
            if (remotePath == "/")
            {

            }
            else
            {
                _uri = "ftp://" + host + "/" + remotePath + "/";
            }
        }
        /// <summary>
        /// 获取当前目录下的列表明细(包含文件和文件夹)
        /// </summary>
        /// <returns></returns>
        public string[] GetFilesDetailList()
        {
            StreamReader reader = null;
            WebResponse response = null;
            try
            {
                StringBuilder result = new StringBuilder();
                FtpWebRequest ftpWebRequest;
                ftpWebRequest = (FtpWebRequest)FtpWebRequest.Create(new Uri(_uri));
                ftpWebRequest.Credentials = new NetworkCredential(_userId, _password);
                ftpWebRequest.Method = WebRequestMethods.Ftp.ListDirectoryDetails;
                response = ftpWebRequest.GetResponse();
                reader = new StreamReader(response.GetResponseStream(), Encoding.Default);
                string line = reader.ReadLine();
                while (line != null)
                {
                    int index = line.LastIndexOf(" ");
                    string name = line.Substring(index + 1);
                    if (name != "." && name != "..")
                    {
                        result.Append(name);
                        result.Append("\n");
                    }
                    line = reader.ReadLine();
                }
                reader.Close();
                response.Close();

                if (result.Length > 0)
                {
                    result.Remove(result.ToString().LastIndexOf("\n"), 1);
                    return result.ToString().Split('\n');
                }
                else
                {
                    return null;
                }
            }
            catch (Exception exception)
            {
                throw new Exception(string.Format("ftp获取当前目录下的列表明细错误：{0}", exception));
            }
            finally
            {
                if (reader != null) reader.Close();
                if (response != null) response.Close();
            }
        }
        /// <summary>
        /// 获取当前目录下文件列表(仅文件)
        /// </summary>
        /// <returns></returns>
        public string[] GetFileList()
        {
            StreamReader reader = null;
            WebResponse response = null;
            try
            {
                StringBuilder result = new StringBuilder();
                FtpWebRequest ftpWebRequest;
                ftpWebRequest = (FtpWebRequest)FtpWebRequest.Create(new Uri(_uri));
                ftpWebRequest.UseBinary = true;
                ftpWebRequest.Credentials = new NetworkCredential(_userId, _password);
                ftpWebRequest.Method = WebRequestMethods.Ftp.ListDirectory;
                response = ftpWebRequest.GetResponse();
                reader = new StreamReader(response.GetResponseStream(), Encoding.Default);
                string line = reader.ReadLine();
                while (line != null)
                {
                    result.Append(line);
                    result.Append("\n");
                    line = reader.ReadLine();
                }
                result.Remove(result.ToString().LastIndexOf("\n"), 1);
                reader.Close();
                response.Close();
                return result.ToString().Split('\n');
            }
            catch (Exception exception)
            {
                throw new Exception(string.Format("ftp获取当前目录下文件列表错误：{0}", exception));
            }
            finally
            {
                if (reader != null) reader.Close();
                if (response != null) response.Close();
            }
        }
        /// <summary>
        /// 下载文件
        /// </summary>
        /// <param name="filePath"></param>
        /// <param name="fileName"></param>
        public void DownloadFile(string webfilname, string filePath, string fileName)
        {
            WebResponse response = null;
            FileStream outputStream = null;
            Stream ftpStream = null;
            string localFilePath = Path.Combine(filePath, fileName);
            try
            {
                using (outputStream = new FileStream(localFilePath, FileMode.Create))
                {
                    FtpWebRequest ftpWebRequest;
                    ftpWebRequest = (FtpWebRequest)FtpWebRequest.Create(new Uri(_uri + webfilname));
                    ftpWebRequest.UseBinary = true;
                    ftpWebRequest.Credentials = new NetworkCredential(_userId, _password);
                    ftpWebRequest.Method = WebRequestMethods.Ftp.DownloadFile;
                    response = ftpWebRequest.GetResponse();
                    ftpStream = response.GetResponseStream();
                    int bufferSize = 2048;
                    int readCount;
                    byte[] buffer = new byte[bufferSize];
                    readCount = ftpStream.Read(buffer, 0, bufferSize);
                    while (readCount > 0)
                    {
                        outputStream.Write(buffer, 0, readCount);
                        readCount = ftpStream.Read(buffer, 0, bufferSize);
                    }
                }
            }
            catch (Exception exception)
            {
                if (File.Exists(localFilePath))
                {
                    File.Delete(localFilePath);
                }
                throw new Exception(string.Format("ftp获取当前目录下文件列表错误：{0}", exception));
            }
            finally
            {
                if (ftpStream != null) ftpStream.Close();
                if (outputStream != null) outputStream.Close();
                if (response != null) response.Close();
            }
        }
        /// <summary>
        /// 切换当前目录
        /// </summary>
        /// <param name="directoryName"></param>
        /// <param name="isRoot">是否绝对路径</param>
        public void GotoDirectory(string directoryName, bool isRoot)
        {
            if (isRoot)
            {
                _remotePath = directoryName;
            }
            else
            {
                _remotePath += directoryName + "/";
            }
            _uri = "ftp://" + _host + "/" + _remotePath + "/";
        }

    }    

    
}
