using System;
using System.Linq;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Threading;
using System.IO;
using SCAN.Data.DataModel;
using SCAN.Data.DataAccess;

namespace SCAN
{
    public partial class Form_Datasync : Form
    {
        public static Form_Datasync _FormInstanceDatasync;

        private string AppPath;

        public Form_Datasync()
        {
            InitializeComponent();
        }

        private void Form_History_Load(object sender, EventArgs e)
        {
            if (System.Windows.Forms.Screen.PrimaryScreen.Bounds.Width == 240)
            {
                resolution.ScreenSize.VGAtoQVGA(this);
            }

            // フォームの最大化・最小化ボタン非表示
            this.MaximizeBox = !this.MaximizeBox;
            this.MinimizeBox = !this.MinimizeBox;
            String path = this.GetType().Assembly.GetModules()[0].FullyQualifiedName;
            Int32 en = path.LastIndexOf("\\");
            AppPath = path.Substring(0, en);

            _FormInstanceDatasync = this;
        }

        private void btnDatasync_Click(object sender, EventArgs e)
        {

        }

        private void btnTankMatching_Click(object sender, EventArgs e)
        {

        }

        private void btnHistory_Click(object sender, EventArgs e)
        {

        }

        private void btnSetting_Click(object sender, EventArgs e)
        {
            //Form frmE = new Form_Setting();
            //frmE.Show();
            //this.Hide();
        }

        private void btnConnectPC_Click(object sender, EventArgs e)
        {
            setButtonUI(sender);

           lib.BtCommLib.openUsb();  
      

            // try to connect
            int max_retry = 10;
            while (lib.BtCommLib.checkUsbStatus() != 1 && max_retry > 0)
            {

                max_retry--;
                Thread.Sleep(1000);

            }

            if (max_retry == 0)
            {
                MessageBox.Show("Please attach it on the cradle.", "Error",
                    MessageBoxButtons.OK, MessageBoxIcon.Exclamation, MessageBoxDefaultButton.Button1);
                btnConnectPC.BackColor = Color.Silver;
                return;
            }

            setButtonUIReady(sender);
            lib.BtCommLib.listen(AppPath + "\\KPListen.txt");
        }
        private void setButtonUI(object sender)
        {
            btnConnectPC.BackColor = Color.Silver;
  
            Button button;
            if (sender is Button)
            {
                button = sender as Button;
          
                button.BackColor = Color.Yellow;
            }

            _FormInstanceDatasync.Update();
        }

        private void setButtonUIReady(object sender)
        {
            btnConnectPC.BackColor = Color.Silver;

            Button button;
            if (sender is Button)
            {
                button = sender as Button;

                button.BackColor = Color.SteelBlue;
            }

            _FormInstanceDatasync.Update();
        }

        private void btnMainMenu_Click(object sender, EventArgs e)
        {
            //importCSV2Db(Form_Login._Form_LoginInstance.CSV_IMPORT_DIRTank_and_material);

            Form_Menu._Form_MenuInstance.Show();
            this.Close();
        }

        private void importCSV2Db(string buffer_dir)
        {
            try
            {


                lib.Utils.mkdir(buffer_dir);

                string line;
                List<FileInfo> files = lib.Utils.listFile(buffer_dir, "*.csv");
                if (files.Count == 0) return;

       

                List<TankAndMaterialMasterModel> lstTankAndMasterModel = new List<TankAndMaterialMasterModel>();
                TankAndMaterialMasterModel objTankAndMasterModel;


                StringBuilder sqlDel = AddAccess.Instant.DeleteAllTankAndMaterialMaster();
                int dbIdxDel = lib.SqliteDb.openDB(Form_Login._Form_LoginInstance.DB_FILE);
                int retDel = Bt.FileLib.SQLite.btSQLiteExecute(dbIdxDel, sqlDel);
                       
                foreach (FileInfo file in files)
                {
              
                    using (StreamReader streamReader = new StreamReader(file.FullName))
                    {
                        while ((line = streamReader.ReadLine()) != null)
                        {

                            List<String> strList = SCAN.lib.CsvParser.Parse(line);
                            if (strList.Count < 10)
                            {
                                strList.Add("");
                            }

                            if (strList[0].ToString().Trim() != "No.") // แถวแรกต้องไม่ใช่หัวคอลัม
                            {

                                objTankAndMasterModel = new TankAndMaterialMasterModel();
                                objTankAndMasterModel.No = strList[0].ToString().Trim();
                                objTankAndMasterModel.HopperNo = strList[1].ToString().Trim();
                                objTankAndMasterModel.HopperQty = strList[2].ToString().Trim();
                                objTankAndMasterModel.TankQty = strList[3].ToString().Trim();
                                objTankAndMasterModel.MatName = strList[4].ToString().Trim();
                                objTankAndMasterModel.Area = strList[5].ToString().Trim();
                                objTankAndMasterModel.MatType = strList[6].ToString().Trim();
                                objTankAndMasterModel.FixNoFixMaster = strList[7].ToString().Trim();
                                objTankAndMasterModel.NoHaveTank = strList[8].ToString().Trim();
                                objTankAndMasterModel.Finish = strList[9].ToString().Trim();
                     
                                StringBuilder sqlInsert = AddAccess.Instant.getAddTankAndMaterialMaster(objTankAndMasterModel);
                                int dbIdx = lib.SqliteDb.openDB(Form_Login._Form_LoginInstance.DB_FILE);
                                int retIns = Bt.FileLib.SQLite.btSQLiteExecute(dbIdx, sqlInsert);
                       

                            }
                        }

                    }
                }


            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            finally
            {
     

            }

            //lib.Utils.removeDirectory(buffer_dir, false);
            lib.SqliteDb.closeDB();
     
        }

  
        private void btnExport_Click(object sender, EventArgs e)
        {
            try
            {
     
                if (Convert.ToInt32(GetAccess.Instant.getreport()) == 0)
                {
                    MessageBox.Show("Data not found");
                    return;
                }



                string buffer_dir = Form_Login._Form_LoginInstance.CSV_EXPORT_DIR;
                outputCSVFile(buffer_dir);

                StringBuilder sqlDelete = AddAccess.Instant.getDeleteafterExport();
                int dbIdx = lib.SqliteDb.openDB(Form_Login._Form_LoginInstance.DB_FILE);
                int retIns = Bt.FileLib.SQLite.btSQLiteExecute(dbIdx, sqlDelete);
                MessageBox.Show("Export Success.");
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
          
        }

        private void outputCSVFile(string buffer_dir)
        {
            List<string[]> workbooks = new List<string[]>();
            List<string[]> rows = new List<string[]>();

            //logger.Log("create dir if not exists [" + buffer_dir + "]");
            //lib.Utils.mkdir(buffer_dir);

            // export success workbook
            string sql = Schedule.getSuccessWorkbookSql();
            lib.SqliteDb.query(sql, ref rows);

            string century = DateTime.Now.ToString("yyyy").Substring(0, 2);

            if (rows.Count > 0)
            {
                // delete if exists

                //lib.Utils.removeFile(buffer_dir + "ResultData_" + DateTime.Now.ToString("dd-M-yyyy") + ".csv");

                using (StreamWriter w = File.AppendText(buffer_dir + "ResultData_" + DateTime.Now.ToString("dd-M-yyyy") + "_" + DateTime.Now.Minute + DateTime.Now.Second + DateTime.Now.Millisecond + ".csv"))
                {
                    w.WriteLine(Schedule.getCsvHeaderColumnName(","));
                    int i = 0;
                    foreach (string[] row in rows)
                    {
                        string[] _row = new string[row.Length + 1];
                        _row[0] = (++i).ToString();
                        Array.Copy(row, 0, _row, 1, row.Length);
                        bool first = true;
                        foreach (string val in _row)
                        {
                            w.Write(String.Format("{0}\"{1}\"", first ? "" : ",", val));
                            first = false;
                        }
                        w.WriteLine("");
                    }
                }
            }


            // delete status 'OK' at HT

            //int dbIdx = lib.SqliteDb.openDB(Form_Login._Form_LoginInstance.DB_FILE);
            //StringBuilder sqldel = Schedule.deleteStatusOK();
            //int retIns = Bt.FileLib.SQLite.btSQLiteExecute(dbIdx, sqldel);



        }


        private void Form_Datasync_KeyDown(object sender, KeyEventArgs e)
        {
            switch (e.KeyCode.ToString())
            {

                case "F1":
                    btnConnectPC_Click(sender, e);

                    break;
                case "F2":
                    btnSetting_Click(sender, e);

                    break;
                case "F3":
                    btnExport_Click(sender, e);

                    break;
                case "F4":
                    btnMainMenu_Click(sender, e);

                    break;

            }
        }

    }
}