using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
namespace FTP_DB_Adapt
{
    class Program
    {
        static System.Data.SqlClient.SqlConnection cn;
        static System.Data.SqlClient.SqlCommand cmd;
        static System.Data.SqlClient.SqlDataAdapter da;
        static  arUtil.FTPClient.FTPClient ftp;
        static CSetting setting;
        static arUtil.Log log;

        static string lastfile = "";
        static DateTime lasttime = DateTime.Now;

        class retdata
        {
            public int count { get; set; }
            public System.Data.DataTable result { get; set; }
            public string message { get; set; }
        }

        static void Main(string[] args)
        {
            //var jstest = JsonConvert.SerializeObject(retval);
            // var jsontest = "{\"count\":1,\"result\":[{\"id\":\"395552\",\"password\":\"B6589FC6AB0DC82CF12099D1C2D40AB994E8410C\",\"nameE\":\"Chikyun.Kim\",\"name\":\"��ġ��\",\"dept\":\"�������� ������� K4�����1��Ʈ\",\"grade\":\"å��\",\"email\":\"Chikyun.Kim@amkor.co.kr\",\"level\":1,\"indate\":\"2018-04-11\",\"outdate\":null";
            /// var json = JObject.Parse(jsontest);
            // // var cnt = json["count"];

            cw("setting load");
            setting = new CSetting();
            setting.Load();
            if (setting.Xml.Exist() == false)
            {
                setting.Xml.CreateFile();
                cw("setting file created");
            }

            if (setting.ftphost == "")
            {
                setting.ftphost = "ftp.amkor.co.kr";
                setting.ftpid = "k4pcbmgr";
                setting.ftppw = "W2$fYiXp";
                setting.Save();
                cw("setting default");
            }
            cw(string.Format("ftp info - {0}", setting.ftphost));


            Properties.Settings.Default["cs"] = setting.connstr; // "Data Source=10.131.15.18;Initial Catalog=EE;Persist Security Info=True;User ID=eeuser;Password=Amkor123!";


            cw("program start v191212-0950" );
            cn = new System.Data.SqlClient.SqlConnection(Properties.Settings.Default.cs);
            DateTime conntime = DateTime.Now;

        
            
            //ftp = new arUtil.FTPClient();
            while(true)
            {
                if(cn.State == System.Data.ConnectionState.Open)
                {
                    if(ftp == null)
                    {
                        ftp = new arUtil.FTPClient.FTPClient();
                        ftp.Host = setting.ftphost;
                        ftp.UserPassword = setting.ftppw;
                        ftp.UserID = setting.ftpid;
                        ftp.Port = 21;
                        cw(string.Format("ftp Initialize {0}",ftp.Host));
                    }
                    
                    //monitor file list
                    string path = "/2D TEST/101369103/Log/QryResult";
                    var list = ftp.directoryListSimple(path);
                    var sqllist = list.Where(t => t.ToLower().EndsWith(".sql"));
                    DateTime findtime = DateTime.Parse("1982-11-23");
                    foreach(var sqlfile in sqllist)
                    {
                        string fn = sqlfile.Substring(0, sqlfile.Length - 3);
                        string resultfile = fn + "json";
                        if (list.Contains(resultfile)) continue;

                        if(lastfile == sqlfile)
                        {
                            var ts = DateTime.Now - lasttime;
                            if (ts.TotalSeconds < 3) continue;  //3초이내 연속 실행 불가
                        }

                        //다운로드전에 무조건 대기해준다.
                        System.Threading.Thread.Sleep(200);

                        //    //이파일명에 해당하는 json 파일을 찾는다.
                        //    string rltfile = 
                        var file_local = AppDomain.CurrentDomain.BaseDirectory + sqlfile;
                        var file_remote = path + "/" + sqlfile;
                        try
                        {
                            if (System.IO.File.Exists(file_local)) System.IO.File.Delete(file_local);
                            cw(string.Format("Down {0} to {1}",file_remote, file_local));
                            lastfile = sqlfile;
                            lasttime = DateTime.Now;
                            if(ftp.Download(file_remote,file_local))
                            {
                                retdata retval = new retdata();
                                retval.count = 0;
                                retval.result = null;
                                retval.message = "";

                               
                                cw("download ok : " + file_remote);

                                var jsonStr = "";
                                var sql = System.IO.File.ReadAllText(file_local, System.Text.Encoding.Default);
                                if (cmd == null) cmd = new System.Data.SqlClient.SqlCommand(sql);

                                var downfi = new System.IO.FileInfo(file_local);
                                if (downfi.Length < 1)
                                {
                                    retval.message = "0byte File Downaloaded : " + file_local;
                                }
                                else  if(sql.Trim() == "")
                                {
                                    retval.message = "No Sql data";
                                }
                                else
                                {
                                    cmd.CommandText = sql;
                                    cmd.Connection = cn;
                                    if (cn.State == System.Data.ConnectionState.Closed) cn.Open();

                                    if (sql.ToLower().StartsWith("select"))
                                    {
                                        cw("select query");
                                        //data table
                                        if (da == null) da = new System.Data.SqlClient.SqlDataAdapter(cmd);
                                        using (var ds = new System.Data.DataSet())
                                        {
                                            try
                                            {
                                                da.Fill(ds);
                                                if (ds != null && ds.Tables.Count > 0)
                                                {
                                                    retval.result = ds.Tables[0];
                                                    retval.count = retval.result.Rows.Count;
                                                }
                                            }
                                            catch (Exception ex)
                                            {
                                                retval.message = ex.Message + ",sql=" + sql;
                                            }
                                        }
                                    }
                                    else
                                    {
                                        cw("non query");
                                        //insert /update/ delete
                                        cmd.Connection = cn;
                                        try
                                        {
                                            retval.count = cmd.ExecuteNonQuery();
                                        }
                                        catch (Exception ex)
                                        {
                                            retval.message = ex.Message + ",sql=" + sql;
                                        }
                                    }

                                    jsonStr = JsonConvert.SerializeObject(retval);
                                    if (jsonStr != "")
                                    {
                                        file_local = AppDomain.CurrentDomain.BaseDirectory + resultfile;
                                        System.IO.File.WriteAllText(file_local, jsonStr, System.Text.Encoding.Default);
                                        cw("result file save : " + file_local);

                                        file_remote = path + "/" + resultfile;
                                        if (!ftp.Upload(file_remote, file_local))
                                            cw("ftp Upload error remote = " + file_remote + "," + file_local);
                                    }
                                }
                            }
                            else
                            {
                                cw("ftp down error remote = " + file_remote);
                            }
                        }
                        catch (Exception ex)
                        {
                            cw("conn error:" + ex.Message);
                        }
                    }

                }
                else
                {
                    var ts = DateTime.Now - conntime;
                    if(ts.TotalSeconds > 5)
                    {
                        try
                        {
                            cw("Try Database Connect ");
                            cn.Open();
                            cw("Database Connected\n\nFTP Monitor ON");
                        }
                        catch (Exception ex)
                        {
                            cw("conn error:" + ex.Message);
                        }
                        finally
                        {
                            conntime = DateTime.Now;
                        }
                    }
                }
                System.Threading.Thread.Sleep(1);
            }
            
        }
        static void cw(string msg,Boolean logon=true)
        {
            if(log == null)
            {
                log = new arUtil.Log();
            }
            if (logon) log.Add(msg);
            Console.WriteLine(msg);
        }

    }
}
