using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace FCOMMON
{
    public partial class fFTPExplorer : Form
    {
        string homePath = string.Empty;
        string curPath = string.Empty;
        arUtil.FTPClient.FTPClient ftp;
        string fn = "ftpExplorer.ini";
        public fFTPExplorer(string title,string path,string ip,string id,string pw,int port=21,Boolean passvie=true)
        {
            InitializeComponent();
            this.Text = string.Format("[FTP] {0}",title);
            this.KeyPreview = true;
            this.KeyDown += (s1, e1) => {
                if (e1.KeyCode == Keys.Escape) this.Close();
            };
            this.listView1.DoubleClick += listView1_DoubleClick;
            this.tbpath.KeyDown += (s1, e1) => {
                if (e1.KeyCode == Keys.Enter)
                    btQuery.PerformClick();
            };
            this.FormClosed += __Closed;
            ftp = new arUtil.FTPClient.FTPClient(ip, id, pw, port, passvie);
            curPath = path;
            homePath = path;

            //홈폴더가 없으면 생성을 한다.
            var list = ftp.directoryListSimple(homePath);
            if(list.Length == 1)
            {
                //폴더를 생성해준다.
                ftp.createDirectory(homePath);

                //하위폴더
                string[] subdir = new string[] { "Source","Document","Draw"};
                foreach (var dir in subdir)
                    ftp.createDirectory(ftp.PathCombine(homePath, dir));
            }

            this.listView1.DragDrop += listView1_DragDrop;
            this.listView1.DragEnter += listView1_DragEnter;
            this.listView1.DragOver += listView1_DragOver;
        }

        void __Closed(object sender, FormClosedEventArgs e)
        {
            //listview column width

            arUtil.INIHelper ini = new arUtil.INIHelper(fn);
            for (int i = 0; i < this.listView1.Columns.Count; i++)
            {
                var curwidth = this.listView1.Columns[i].Width;
                ini.set_Data("colsize", "index_" + i.ToString(), curwidth.ToString());
            }
            ini.Flush();

            //string item = "ftp_lv_col_";
            //for (int i = 0; i < this.listView1.Columns.Count; i++)
            //{
            //    var curwidth =  this.listView1.Columns[i].Width;
            //    Pub.setting.Xml.set_Data(item + i.ToString(),curwidth.ToString());
            //}
            //Pub.setting.Save();
        }

        private void __Load(object sender, EventArgs e)
        {
            this.tbpath.Text = this.curPath;// Pub.setting.ftp_path;
            if (this.tbpath.Text == "") tbpath.Text = "/";
            timer1.Start();

            //listview column width
            //string item = "ftp_lv_col_";

            if (System.IO.File.Exists(fn) == false) return;
            arUtil.INIHelper ini = new arUtil.INIHelper(fn);
            for (int i = 0; i < this.listView1.Columns.Count; i++)
            {
                var cwid = ini.get_Data("colsize", "index_" + i.ToString(), "0");
                this.listView1.Columns[i].Width = int.Parse(cwid);
            }
            btQuery.PerformClick();
        }
        void listView1_DragOver(object sender, DragEventArgs e)
        {
            this.Cursor = Cursors.Hand;
        }

        void listView1_DragEnter(object sender, DragEventArgs e)
        {
            e.Effect = DragDropEffects.All;
        }

        void listView1_DragDrop(object sender, DragEventArgs e)
        {
            string[] files = (string[])e.Data.GetData(DataFormats.FileDrop, false);
            if (files.Length < 1) return;
            string msg = string.Format("{0}건의 파일을 업로드 하시겠습니까?",files.Length);
            if (FCOMMON.Util.MsgQ(msg) != System.Windows.Forms.DialogResult.Yes) return;
            foreach(var fileName in files)
            {
                System.IO.FileInfo fi = new System.IO.FileInfo(fileName);
                string remote = tbpath.Text      + "/" + fi.Name;
                ftp.Upload(remote, fi.FullName);
            }
            btQuery.PerformClick();
        }


        void listView1_DoubleClick(object sender, EventArgs e)
        {
            var path = listView1.SelectedItems[0].Text;
            var newpath = string.Empty;
            if (path == "..")
            {
                if( this.homePath.Replace("/","") == curPath.Replace("/",""))
                {
                    FCOMMON.Util.MsgE("홈 디렉토리 입니다.");
                    return;
                } else  newpath = ftp.getParent(curPath);
            }   
            else
                newpath = ftp.PathCombine(curPath, path);

            search(newpath);
        }

       
        private void button1_Click(object sender, EventArgs e)
        {
            if (this.tbpath.Text == "/") this.tbpath.Text = homePath;
            search(this.tbpath.Text);
            tbpath.Focus();
            tbpath.SelectAll();
        }

        void search(string path)
        {
            if (path == "") path = "/";
            curPath = path;
            tbpath.Text = curPath;

            this.listView1.Items.Clear();
            this.progressBar1.Value = 0;


           // var list = ftp.directoryListSimple("/201");

            var lvup = listView1.Items.Add("..");
            lvup.SubItems.Add("");
            lvup.SubItems.Add("");
            lvup.SubItems.Add("");


            var ftpdir = ftp.ListDirectoryDetail(path);
            if(ftpdir == null)
            {
                //Util.MsgE(ftp.errorMessage);
                return;
            }
          
            this.progressBar1.Maximum = ftpdir.Count;
            var OrderData = ftpdir.OrderBy(t => t.FileType).OrderBy(t=>t.Filename);
           
            foreach (var item in OrderData)
            {
                this.progressBar1.Value += 1;
                if (item.Filename == ".") continue;
                var lv = listView1.Items.Add(item.Filename);
                lv.SubItems.Add(item.FileType.ToString());
                lv.SubItems.Add(item.Size.ToString());
                lv.SubItems.Add(item.FileDateTime.ToString());
                if (item.FileType ==  arUtil.FTPClient.FTPfileInfo.DirectoryEntryTypes.Directory) lv.ForeColor = Color.Blue;
            }
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            this.lbPath.Text = curPath;
        }

        private void uploadToolStripMenuItem_Click(object sender, EventArgs e)
        {
            OpenFileDialog od = new OpenFileDialog();
            if (od.ShowDialog() != System.Windows.Forms.DialogResult.OK) return;
            //이파일을 현재 위치에 업로드 한다.
            System.IO.FileInfo fi = new System.IO.FileInfo(od.FileName);
            string newfile = ftp.PathFileCombine(curPath, fi.Name);
            if (!ftp.Upload(newfile, od.FileName))
                Util.MsgE("upload error");
            search(curPath);
        }

        private void downLoadToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (this.listView1.SelectedItems.Count < 1) return;

            //이파일을 현재 위치에 업로드 한다.
            var selfile = this.listView1.SelectedItems[0];
            var remotefile = ftp.PathFileCombine(curPath, selfile.Text);
            var onlyfilename = remotefile.Substring(remotefile.LastIndexOf("/")+1);
                        
            SaveFileDialog od = new SaveFileDialog();
            od.Filter = "All files|*.*";
            od.FilterIndex = 1;
            od.FileName = onlyfilename;
            
            if (od.ShowDialog() != System.Windows.Forms.DialogResult.OK) return;
            
            System.IO.FileInfo fi = new System.IO.FileInfo(od.FileName);
            string newfile = ftp.PathFileCombine(curPath, fi.Name);
            if (!ftp.Download(remotefile,od.FileName))
                Util.MsgE("Download error");
            search(curPath);
        }
    }
}
