using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Globalization;
using WpfLocalization;
using System.Threading;
using System.Data.SqlClient;
using System.Data;
using System.Diagnostics;
using System.IO;
using System.Collections;
using System.IO.Ports;
using System.Collections.ObjectModel;
using System.Reflection;
using System.Configuration;
using System.Collections.Specialized;
using System.Data.SqlServerCe;
using System.ComponentModel;
using System.Windows.Threading;

using System.Data.OleDb;


namespace WpfApplication19
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    /// 

    public partial class MainWindow : Window
    {
        private bool isFullScreen = false;
        private Debug dw;
        public SqlConnection configConn, masterConn, transConn, proConn;
        private SqlCeConnection _opConn;
        //private SqlDataReader reader;
        string[] obTables = new string[] {"BEL-MAS-1", "BEL-MAS-3", "E-MAS-1", "E-MAS-3", 
                                             "MG-MAS-1", "MG-MAS-3", "V-MAS-1", "V-MAS-3"};

        public SerialPort comport = new SerialPort();
        ObservableCollection<MeasurePoint> mps;
        int nextCol = 3;

        bool isMiddle = false, _haveMiddle = false;
        bool _isIn = false;
        public string inStarGS = "";
        public string midGS = "";
        string sMi16, sMi20, kind;

        enum RecordTypes { TopUnder, InOut }
        string[] masViews = new string[] { "bel_master_view", "e_master_view", "mg_master_view", "v_master_view" };

        List<string> list;
        string header;
        Stack<string> _lastAction = new Stack<string>();
        bool _isTkx = false;
        DateTime _lastTimeDataPort;
        bool _isCheck = false;
        DailyCheck _dc;
        RLAlert _rl;
        public RLWindow _rlWindow;
        Encoding encAscii = Encoding.ASCII;

        Dictionary<string, string> rolesDescription = new Dictionary<string, string>
        {
               {"qa_staff", "QA Staff"},{"user","User"}, {"admin", "Administrator"}, {"qa_man", "QA Ass't Manager"}
        };

        Dictionary<string, string> _sideMap = new Dictionary<string, string>
        {
               {"out", "in"},{"in","under"}, {"rim", "base"}, {"top", "under"}, {"outer", "inner"}
        };
        private double out0, out1;
        private double in0, in1;

        MeasurePoint currentMP;
        string currentColumn;
        Debug _debugWindow;
        Thread _aThread, _bThread;
        bool _clearThread = false, _canSent = true;
        int _pattern = 1;
        string _updated_at;
        private int _obLimit, _obCount, _ocLimit, _ocCount, _rhLimit, _rhCount;
        bool _isOver = false;
        bool _isFirstMeasure = true;
        DateTime _startUsing = new DateTime();
        int _usingTime;
        bool _isExisting = false;
        private List<string> _agreementList = new List<string>();
        string _currentValue, _prevValue = null;
        double _lower1, _upper1, _lower2, _upper2;
        string strAccessConnEMASTER = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=\\\\192.168.0.253\\mgt\\master\\E-Master.mdb;Mode=Share Deny None";
        string strAccessConnBELMASTER = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=\\\\192.168.0.253\\mgt\\master\\BEL-Master.mdb;Mode=Share Deny None";
        string strAccessConnMGMASTER = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=\\\\192.168.0.253\\mgt\\master\\MG-Master.mdb;Mode=Share Deny None";
        string strAccessConnVMASTER = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=\\\\192.168.0.253\\mgt\\master\\V-Master.mdb;Mode=Share Deny None";
     
        OleDbConnection accessConnEMASTER = null;
        OleDbConnection accessConnBELMASTER = null;
        OleDbConnection accessConnMGMASTER = null;
        OleDbConnection accessConnVMASTER = null;
        OleDbConnection tempConn = null;
        string obCondition;

        public MainWindow()
        {
            InitializeComponent();
            //dw = new Debug();
            //dw.Show();
            Thread.CurrentThread.CurrentCulture = new CultureInfo("en-US");

            //Thread.CurrentThread.CurrentCulture.DateTimeFormat.ShortDatePattern = "dd/MM/yyyy";
            //Thread.CurrentThread.CurrentCulture = ci;

            //OBInterface obInterface = new OBInterface(comport);
            /*
            _debugWindow = new Debug();
            _debugWindow.Topmost = true;
            _debugWindow.Show();
             */

            // comment for testing
            LoginWindow loginWindow = new LoginWindow();
            var r = loginWindow.ShowDialog();
            if (r == false)
                return;

            //this.Hide();
            //loginWindow.Topmost = true;


            initSys();

            //forTesting();
            //for old ob box 
            //_aThread = new Thread(new ThreadStart(Sender));
            //no need for mitutoyo
           // _aThread = new Thread(new ThreadStart(Sender2));
           // _aThread.Start();


            //DispatcherTimer _timer = new DispatcherTimer();


            lotNo.Focus();
        }
        public void ResetHeaderUsage()
        {
            _isOver = false;
            if (header == "OB")
            {
                _obCount = 0;
            }
            else if (header == "OC")
            {
                _ocCount = 0;
            }
            else if (header == "RH")
            {
                _rhCount = 0;

            }

        }
        public void Sender2()
        {
            while (comport.IsOpen && _clearThread == false)
            {
                //Console.WriteLine("Hello");
                //string readCommand = String.Format("{0}{1}{2}{3}",0x002, 0x052, 0x031, 0x00D);
                string readCommand = encAscii.GetString(new byte[] { 0x02, 0x52, 0x31, 0x0D });

                if (_canSent == true)
                {
                    try
                    {
                        comport.Write(readCommand);
                        Thread.Sleep(500);
                    }
                    catch
                    {
                        Thread.Sleep(1000);
                    }
                }

                /*
                if (!_debugWindow.Dispatcher.CheckAccess())
                {
                    _debugWindow.Dispatcher.Invoke(
                      System.Windows.Threading.DispatcherPriority.Normal,
                      new Action(
                        delegate()
                        {
                            _debugWindow.debugTextBox.AppendText("Sending\n");
                        }
                    ));
                }
                else
                {
                    _debugWindow.debugTextBox.AppendText("Sending\n");
                }*/

            }
        }
        public void Sender()
        {
            while (comport.IsOpen && _clearThread == false)
            {
                //Console.WriteLine("Hello");
                comport.Write("S");
                Thread.Sleep(500);
                /*
                if (!_debugWindow.Dispatcher.CheckAccess())
                {
                    _debugWindow.Dispatcher.Invoke(
                      System.Windows.Threading.DispatcherPriority.Normal,
                      new Action(
                        delegate()
                        {
                            _debugWindow.debugTextBox.AppendText("Sending\n");
                        }
                    ));
                }
                else
                {
                    _debugWindow.debugTextBox.AppendText("Sending\n");
                }*/

            }
        }
        public void AutoSaveData()
        {
            //Thread.Sleep(1500);
            if (_prevValue == null)
            {
                _prevValue = _currentValue;
            }
            TimeSpan ts = DateTime.Now - _lastTimeDataPort;
            //if (ts.Seconds >= 1 && _lastTimeDataPort != DateTime.MinValue)
            if (_lastTimeDataPort != DateTime.MinValue)
            {

                _lastTimeDataPort = DateTime.MinValue;
                if (_prevValue == _currentValue)
                {
                    saveCellBtn.RaiseEvent(new RoutedEventArgs(Button.ClickEvent, saveCellBtn));
                }
                else
                {
                    _prevValue = null;
                }

            }

        }
        private void forTesting()
        {
            var r = GetRecordType("114-78469F");
            Console.WriteLine(r);

        }

        private void initSys()
        {
            initDatabaseConnection();

            initCOMPort();

            //initMachineList();
            SqlDataReader reader = Utils.Query(proConn, "select * from sys_configs");
            string title;

            resetMenu();

            while (reader.Read())
            {
                title = reader["title"].ToString();
                //value = reader["value"];
                switch (title)
                {
                    case "ob_limit":
                        _obLimit = Convert.ToInt32(reader["value"]);
                        break;
                    case "oc_limit":
                        _ocLimit = Convert.ToInt32(reader["value"]);
                        break;
                    case "rh_limit":
                        _rhLimit = Convert.ToInt32(reader["value"]);
                        break;
                    default:
                        //MessageBox.Show("Bad config variable :"+title);
                        break;
                }
            }

            reader.Close();
        }

        private void resetMenu()
        {
            if (GlobalVars.user.empid == "root" ||
                         GlobalVars.user.roles.Find(
                         delegate(string s)
                         {
                             return s == "admin";
                         }) != null)
            {
                configMenu.Visibility = Visibility.Visible;
            }
            else
            {
                configMenu.Visibility = Visibility.Collapsed;
            }
        }

        public void setFilterLogData(string q)
        {
            _isExisting = true;
            this._updated_at = q;

        }
        private List<string> GetRecordType(string pro2)
        {
            foreach (var view in masViews)
            {

                SqlCommand cmd = proConn.CreateCommand();
                string sql = @"
              select * from [" + view + "] v where v.PRO2='" + pro2 + "'";
                cmd.CommandText = sql;
                //Console.WriteLine(sql);
                SqlDataReader reader = cmd.ExecuteReader();

                if (!reader.HasRows)
                {
                    reader.Close();
                    continue;
                }
                bool hasIn, hasOut;


                while (reader.Read())
                {

                    var mi17 = reader["MI17"].ToString();
                    if (string.IsNullOrEmpty(mi17) || mi17 == "NULL")
                    {
                        hasOut = false;
                    }
                    else
                    {
                        hasOut = true;
                    }

                    string mi21 = reader["MI21"].ToString();
                    if (string.IsNullOrEmpty(mi21) || mi21 == "NULL")
                    {
                        hasIn = false;
                    }
                    else
                    {
                        hasIn = true;
                    }
                    List<string> rList = new List<string>();
                    if (_isTkx == true)
                    {
                        rList.Add("FA1");
                        rList.Add("FA2");
                        //rList.Add("MID");
                        //rList.Add("IN*");
                        reader.Close();
                        point1Label.Content = "FA";
                        point2Label.Content = "None";
                        return rList;
                    }
                    if (view == "bel_master_view" || view == "e_master_view" || view == "mg_master_view")
                    {


                        if (reader["MP45"].ToString() != "NULL" && !string.IsNullOrEmpty(reader["MP45"].ToString().Trim()))
                        {
                            rList.Add(reader["MP45"].ToString().ToUpper());

                        }
                        point1Label.Content = reader["MP45"].ToString().ToUpper();
                        //rList.Add("MID");
                        //rList.Add("IN*");
                        if (reader["MP49"].ToString() != "NULL" && !string.IsNullOrEmpty(reader["MP49"].ToString().Trim()))
                        {
                            rList.Add(reader["MP49"].ToString().ToUpper());
                            point2Label.Content = reader["MP49"].ToString().ToUpper();
                        }
                        else
                        {
                            if (hasIn == true)
                            {
                                var side = reader["MP45"].ToString().ToLower();
                                rList.Add(_sideMap[side].ToUpper());
                                point2Label.Content = _sideMap[side].ToUpper();
                            }
                        }

                        reader.Close();

                        return rList;
                    }
                    else
                    {
                        if (reader["MP34"].ToString() != "NULL" && !string.IsNullOrEmpty(reader["MP34"].ToString().Trim()))
                        {
                            rList.Add(reader["MP34"].ToString().ToUpper());

                        }
                        point1Label.Content = reader["MP34"].ToString().ToUpper();
                        //rList.Add("MID");
                        //rList.Add("IN*");
                        if (reader["MP39"].ToString() != "NULL" && !string.IsNullOrEmpty(reader["MP39"].ToString().Trim()))
                        {
                            rList.Add(reader["MP39"].ToString().ToUpper());
                            point2Label.Content = reader["MP39"].ToString().ToUpper();
                        }
                        else
                        {
                            if (hasIn == true)
                            {
                                var side = reader["MP34"].ToString().ToLower();
                                rList.Add(_sideMap[side].ToUpper());
                                point2Label.Content = _sideMap[side].ToUpper();
                            }
                        }

                        reader.Close();
                        return rList;
                    }
                }
            }

            return null;
        }
        //for old ob box
        void DataReceivedHandler(
                       object sender,
                       SerialDataReceivedEventArgs e)
        {
            SerialPort sp = (SerialPort)sender;
            byte[] data = new byte[2];
            data[0] = (byte)sp.ReadByte();
            data[1] = (byte)sp.ReadByte();
            //byte[] data = new byte[2];
            //int nByteRead = sp.Read(data, 0, 2);
            _lastTimeDataPort = DateTime.Now;
            byte[] bcddata = new byte[4];
            byte anddata = 240;
            byte tempdata;
            if (_pattern == 1)
            {
                anddata = (byte)240;
                bcddata[1] = (byte)(data[0] & anddata);
                bcddata[1] = (byte)(bcddata[1] >> 4);
                bcddata[3] = (byte)(data[1] & anddata);
                bcddata[3] = (byte)(bcddata[3] >> 4);

                anddata = (byte)1;
                bcddata[0] = (byte)(data[0] & (byte)anddata);
                anddata = (byte)15;
                bcddata[2] = (byte)(data[1] & (byte)anddata);

                tempdata = bcddata[3];
                bcddata[3] = (byte)(tempdata & (byte)1);
                bcddata[3] = (byte)(bcddata[3] << 1);
                tempdata = (byte)(tempdata >> 1);

                bcddata[3] = (byte)(bcddata[3] | (tempdata & (byte)1));
                bcddata[3] = (byte)(bcddata[3] << 1);
                tempdata = (byte)(tempdata >> 1);

                bcddata[3] = (byte)(bcddata[3] | (tempdata & (byte)1));
                bcddata[3] = (byte)(bcddata[3] << 1);
                tempdata = (byte)(tempdata >> 1);
                bcddata[3] = (byte)(bcddata[3] | (tempdata & (byte)1));

                tempdata = bcddata[2];
                bcddata[2] = (byte)(tempdata & (byte)1);
                bcddata[2] = (byte)(bcddata[2] << 1);
                tempdata = (byte)(tempdata >> 1);

                bcddata[2] = (byte)(bcddata[2] | (tempdata & (byte)1));
                bcddata[2] = (byte)(bcddata[2] << 1);
                tempdata = (byte)(tempdata >> 1);

                bcddata[2] = (byte)(bcddata[2] | (tempdata & (byte)1));
                bcddata[2] = (byte)(bcddata[2] << 1);
                tempdata = (byte)(tempdata >> 1);
                bcddata[2] = (byte)(bcddata[2] | (tempdata & (byte)1));
            }
            else
            {
                anddata = (byte)240;
                bcddata[1] = (byte)(data[0] & anddata);
                bcddata[1] = (byte)(bcddata[1] >> 4);
                bcddata[3] = (byte)(data[1] & anddata);
                bcddata[3] = (byte)(bcddata[3] >> 4);
                anddata = (byte)1;
                bcddata[0] = (byte)(data[0] & anddata);
                anddata = (byte)15;
                bcddata[2] = (byte)(data[1] & anddata);
            }
            Console.WriteLine("Data Received: {0}", data.Length);
            foreach (byte element in data)
            {
                Console.WriteLine("{0} = {1}", element, (char)element);

            }
            foreach (byte element in bcddata)
            {
                Console.WriteLine("oo {0} = {1}", element, element);
            }
            //Console.WriteLine("{0}.{1}{2}", Convert.ToString(bcddata[1]), Convert.ToString(bcddata[2]), Convert.ToString(bcddata[3]));

            string outputString = string.Format("{0}.{1}{2}", bcddata[1], bcddata[2], bcddata[3]);
            //_currentValue = outputString;
            //_currentValue = outputString;
            if (!readingBox.Dispatcher.CheckAccess())
            {
                readingBox.Dispatcher.Invoke(
                  System.Windows.Threading.DispatcherPriority.Normal,
                  new Action(
                    delegate()
                    {
                        readingBox.Text = outputString;
                        if (_dc != null)
                        {
                            _dc.measureBlock.Text = outputString;
                        }
                        if(_rlWindow != null)
                        {
                            _rlWindow.readingBox.Text = outputString;
                        }
                        //_dc.measureBlock.Text = outputString;
                    }
                ));
            }
            //readingBox.Text = outputString;
        }


        //for new ob box
        void DataReceivedHandler2(
                       object sender,
                       SerialDataReceivedEventArgs e)
        {
            _canSent = false;
            SerialPort sp = (SerialPort)sender;
            byte[] data = new byte[11];

            
            bool readError = false;
            for (int i = 0; i < 11; i++)
            {
                try
                {
                    data[i] = (byte)sp.ReadByte();
                }
                catch
                {
                    readError = true;
                    break;
                }
            }
            Console.WriteLine(data);
            //data[0] = (byte)sp.ReadByte();
            //data[1] = (byte)sp.ReadByte();

            if (readError == true)
                return;
            //byte[] data = new byte[2];
            //int nByteRead = sp.Read(data, 0, 2);
            _lastTimeDataPort = DateTime.Now;
            //Console.WriteLine("{0}.{1}{2}", Convert.ToString(bcddata[1]), Convert.ToString(bcddata[2]), Convert.ToString(bcddata[3]));
            //string outputString = string.Format("{0}{1}{2}{3}{4}{5}{6}", data[1], data[2], data[3], data[4], data[5], data[6], data[7]);
            string outputString = encAscii.GetString(new byte[] { data[3], data[4], data[5], data[6], data[7] });
            //_currentValue = outputString;
            //_currentValue = outputString;
            if (!readingBox.Dispatcher.CheckAccess())
            {
                readingBox.Dispatcher.Invoke(
                  System.Windows.Threading.DispatcherPriority.Normal,
                  new Action(
                    delegate()
                    {
                        if (data[9] == '1')
                        {
                            readingBox.Text = "Error";
                        }
                        else
                        {
                            readingBox.Text = outputString;
                        }
                        if (_dc != null)
                        {
                            _dc.measureBlock.Text = outputString;
                        }
                        //_dc.measureBlock.Text = outputString;
                    }
                ));
            }
            _canSent = true;
            //readingBox.Text = outputString;
        }

        void DataReceivedHandler3(
                   object sender,
                   SerialDataReceivedEventArgs e)
        {
            _canSent = false;
            Console.WriteLine("data rec = "+e.ToString());
            SerialPort sp = (SerialPort)sender;
            int nByte = 40;
            byte[] data = new byte[nByte];
            Console.WriteLine("Handler3");
            bool readError = false;
            //Console.WriteLine("Front mit "+ sp.ReadLine());
            var temp = sp.ReadLine();
            //if (temp == "\r" || (temp.IndexOf("Dbar") != -1))
                //return;
            for (int i = 0; i < temp.Length; i++)
            {
                //Console.WriteLine(sp.ReadByte().ToString());
                //data[i] = (byte)sp.ReadByte();
                data[i] = (byte)temp[i];
                Console.WriteLine(data[i]);

            }


            //data[0] = (byte)sp.ReadByte();
            //data[1] = (byte)sp.ReadByte();
            //MessageBox.Show(System.Text.Encoding.UTF8.GetString(data));
            if (readError == true)
                return;
            //byte[] data = new byte[2];
            //int nByteRead = sp.Read(data, 0, 2);
            _lastTimeDataPort = DateTime.Now;
            //Console.WriteLine("{0}.{1}{2}", Convert.ToString(bcddata[1]), Convert.ToString(bcddata[2]), Convert.ToString(bcddata[3]));
            //string outputString = string.Format("{0}{1}{2}{3}{4}{5}{6}", data[1], data[2], data[3], data[4], data[5], data[6], data[7]);
            string outputString = encAscii.GetString(new byte[] { data[5], data[6], data[7], data[8], data[9], data[10], data[11] });
            //_currentValue = outputString;
            //_currentValue = outputString;
            if (!readingBox.Dispatcher.CheckAccess())
            {
                readingBox.Dispatcher.Invoke(
                  System.Windows.Threading.DispatcherPriority.Normal,
                  new Action(
                    delegate()
                    {
                        //if (data[9] == '1')
                        //{
                        // readingBox.Text = "Error";
                        //}
                        //else
                        //{
                        readingBox.Text = outputString;
                        //}
                        if (_dc != null)
                        {
                            _dc.measureBlock.Text = outputString;
                        }
                        if (_rlWindow != null)
                        {
                            _rlWindow.readingBox.Text = outputString;
                        }
                        //_dc.measureBlock.Text = outputString;
                    }
                ));
            }
            _canSent = true;
            //readingBox.Text = outputString;
            //Console.WriteLine("port data " + temp);
                  
        }
        //for temporary rh2
        void DataReceivedHandler5(
                object sender,
                SerialDataReceivedEventArgs e)
        {
            _canSent = false;
            Console.WriteLine("data rec = " + e.ToString());
            SerialPort sp = (SerialPort)sender;
            int nByte = 40;
            byte[] data = new byte[nByte];
            Console.WriteLine("Handler3");
            bool readError = false;
            //Console.WriteLine("Front mit "+ sp.ReadLine());
            var temp = sp.ReadLine();
            //if (temp == "\r" || (temp.IndexOf("Dbar") != -1))
            //return;
            


            //data[0] = (byte)sp.ReadByte();
            //data[1] = (byte)sp.ReadByte();
            //MessageBox.Show(System.Text.Encoding.UTF8.GetString(data));
            if (readError == true)
                return;
            //byte[] data = new byte[2];
            //int nByteRead = sp.Read(data, 0, 2);
            _lastTimeDataPort = DateTime.Now;
            //Console.WriteLine("{0}.{1}{2}", Convert.ToString(bcddata[1]), Convert.ToString(bcddata[2]), Convert.ToString(bcddata[3]));
            //string outputString = string.Format("{0}{1}{2}{3}{4}{5}{6}", data[1], data[2], data[3], data[4], data[5], data[6], data[7]);
            string outputString = temp.Substring(7, 5).Trim();
            float o = float.Parse(outputString, CultureInfo.InvariantCulture.NumberFormat);
            string rawString = o.ToString("0.##");
            o = o - 70;
            outputString = o.ToString("0.##");

            //_currentValue = outputString;
            //_currentValue = outputString;
            if (!readingBox.Dispatcher.CheckAccess())
            {
                readingBox.Dispatcher.Invoke(
                  System.Windows.Threading.DispatcherPriority.Normal,
                  new Action(
                    delegate ()
                    {
                        //if (data[9] == '1')
                        //{
                        // readingBox.Text = "Error";
                        //}
                        //else
                        //{
                        readingBox.Text = outputString;
                        processedBox.Text = rawString;
                        //}
                        if (_dc != null)
                        {
                            _dc.measureBlock.Text = outputString;
                        }
                        if (_rlWindow != null)
                        {
                            _rlWindow.readingBox.Text = outputString;
                        }
                        //_dc.measureBlock.Text = outputString;
                    }
                ));
            }
            _canSent = true;
            //readingBox.Text = outputString;
            //Console.WriteLine("port data " + temp);

        }
        //new HRH
        void DataReceivedHandler6(
               object sender,
               SerialDataReceivedEventArgs e)
        {
            _canSent = false;
            Console.WriteLine("data rec = " + e.ToString());
            SerialPort sp = (SerialPort)sender;
            int nByte = 40;
            byte[] data = new byte[nByte];
            Console.WriteLine("Handler6");
            bool readError = false;
            //Console.WriteLine("Front mit "+ sp.ReadLine());
            var temp = sp.ReadLine();
            //if (temp == "\r" || (temp.IndexOf("Dbar") != -1))
            //return;



            //data[0] = (byte)sp.ReadByte();
            //data[1] = (byte)sp.ReadByte();
            //MessageBox.Show(System.Text.Encoding.UTF8.GetString(data));
            if (readError == true)
                return;
            //byte[] data = new byte[2];
            //int nByteRead = sp.Read(data, 0, 2);
            _lastTimeDataPort = DateTime.Now;
            //Console.WriteLine("{0}.{1}{2}", Convert.ToString(bcddata[1]), Convert.ToString(bcddata[2]), Convert.ToString(bcddata[3]));
            //string outputString = string.Format("{0}{1}{2}{3}{4}{5}{6}", data[1], data[2], data[3], data[4], data[5], data[6], data[7]);
            //string outputString = temp.Substring(8, 4).Trim();
            string outputString = temp.Substring(6, 6).Trim().Replace(" ", "");
            float o = float.Parse(outputString, CultureInfo.InvariantCulture.NumberFormat);
            string rawString = o.ToString("0.##");
            //o = o - 70;
            outputString = o.ToString("0.##");

            //_currentValue = outputString;
            //_currentValue = outputString;
            if (!readingBox.Dispatcher.CheckAccess())
            {
                readingBox.Dispatcher.Invoke(
                  System.Windows.Threading.DispatcherPriority.Normal,
                  new Action(
                    delegate ()
                    {
                        //if (data[9] == '1')
                        //{
                        // readingBox.Text = "Error";
                        //}
                        //else
                        //{
                        readingBox.Text = outputString;
                        processedBox.Text = rawString;
                        //}
                        if (_dc != null)
                        {
                            _dc.measureBlock.Text = outputString;
                        }
                        if (_rlWindow != null)
                        {
                            _rlWindow.readingBox.Text = outputString;
                        }
                        //_dc.measureBlock.Text = outputString;
                    }
                ));
            }
            _canSent = true;
            //readingBox.Text = outputString;
            //Console.WriteLine("port data " + temp);

        }
        // rh3
        void DataReceivedHandler4(
                  object sender,
                  SerialDataReceivedEventArgs e)
        {
            _canSent = false;
            Console.WriteLine("data rec = " + e.ToString());
            SerialPort sp = (SerialPort)sender;
            byte[] data = new byte[54];
            Console.WriteLine("Handler3");
            bool readError = false;
            //Console.WriteLine("Front mit "+ sp.ReadLine());
            var temp = sp.ReadLine();
            //var temp = sp.ReadLine();
            Console.WriteLine("data from machine :" + temp);
            if (temp == "\r" || (temp.IndexOf("Dbar") != -1) || temp[0] == '-')
                return;
            for (int i = 0; i < 54; i++)
            {
                //Console.WriteLine(sp.ReadByte().ToString());
                //data[i] = (byte)sp.ReadByte();
                data[i] = (byte)temp[i];
                Console.WriteLine(data[i]);

            }


            //data[0] = (byte)sp.ReadByte();
            //data[1] = (byte)sp.ReadByte();
            //MessageBox.Show(System.Text.Encoding.UTF8.GetString(data));
            if (readError == true)
                return;
            //byte[] data = new byte[2];
            //int nByteRead = sp.Read(data, 0, 2);
            _lastTimeDataPort = DateTime.Now;
            //Console.WriteLine("{0}.{1}{2}", Convert.ToString(bcddata[1]), Convert.ToString(bcddata[2]), Convert.ToString(bcddata[3]));
            //string outputString = string.Format("{0}{1}{2}{3}{4}{5}{6}", data[1], data[2], data[3], data[4], data[5], data[6], data[7]);
            string outputString = encAscii.GetString(new byte[] { data[16], data[17], data[18], data[19], data[20] });
            //_currentValue = outputString;
            //_currentValue = outputString;
            if (!readingBox.Dispatcher.CheckAccess())
            {
                readingBox.Dispatcher.Invoke(
                  System.Windows.Threading.DispatcherPriority.Normal,
                  new Action(
                    delegate ()
                    {
                        //if (data[9] == '1')
                        //{
                        // readingBox.Text = "Error";
                        //}
                        //else
                        //{
                        readingBox.Text = outputString;
                        //}
                        if (_dc != null)
                        {
                            _dc.measureBlock.Text = outputString;
                        }
                        if (_rlWindow != null)
                        {
                            _rlWindow.readingBox.Text = outputString;
                        }
                        //_dc.measureBlock.Text = outputString;
                    }
                ));
            }
            _canSent = true;
            //readingBox.Text = outputString;
            //Console.WriteLine("port data " + temp);

        }
       
        void DataErrorHandler3(
                   object sender,
                   SerialErrorReceivedEventArgs e)
        {
            Console.WriteLine("data error "+e.ToString());

        }
        private void initCOMPort()
        {
            Console.WriteLine("Comport is Call");
            if (comport.IsOpen)
                comport.Close();
            //else
            //{

                comport.PortName = Utils.getSetting("machinePort");
                /*
                comport.BaudRate = int.Parse(Utils.getSetting("baudRate"));
                comport.DataBits = int.Parse(Utils.getSetting("dataBits"));
                comport.StopBits = (StopBits)Enum.Parse(typeof(StopBits), Utils.getSetting("stopBits"));
                comport.Parity = (Parity)Enum.Parse(typeof(Parity), Utils.getSetting("parity"));
                */
                // for old ob box version
                //comport.DataReceived += new SerialDataReceivedEventHandler(DataReceivedHandler);
                comport.StopBits = StopBits.Two;
                Console.WriteLine("Comport data "+comport.BaudRate+" "+comport.PortName+ " "+comport.Parity+ " "+comport.DataBits+" "+comport.StopBits);

            //rh 2
            //comport.DataReceived += new SerialDataReceivedEventHandler(DataReceivedHandler3);
            //rh2 temporary measurement
            //#  1:  129.9 HRH Tol:HI
            //comport.DataReceived += new SerialDataReceivedEventHandler(DataReceivedHandler5);
            comport.DataReceived += new SerialDataReceivedEventHandler(DataReceivedHandler6);

            //rh 3 maybe
            //handler 2 for ob3
            //comport.DataReceived += new SerialDataReceivedEventHandler(DataReceivedHandler4);
            //comport.ErrorReceived += new SerialErrorReceivedEventHandler(DataErrorHandler3);
            //comport.ErrorReceived += new SerialErrorReceivedEventHandler(DataErrorHandler3);
            bool error = false;

                try
                {
                    comport.RtsEnable = true;
                    comport.DtrEnable = true;
                    Console.WriteLine("Openning Comport");
                    comport.Open();
                    if (comport.IsOpen == true)
                    {
                        Console.WriteLine("Open .. Done ");
                    }
                    //Thread.Sleep(1000);
                    //comport.Close();
                    //MessageBox.Show("Open Port Success");
                }
                catch (UnauthorizedAccessException) { error = true; }
                catch (IOException) { error = true; }
                catch (ArgumentException) { error = true; }
                if (error)
                {
                    MessageBox.Show("Open Port Fail");
                }
            //}
        }

        private void initDatabaseConnection()
        {


            try
            {
                _opConn = Utils.createSqlCeConnection("operatingDbCS");
                // Sample usage
                /*
                SqlCeDataReader reader;
                reader = Utils.Query(_opConn, "select * from UsingTime");
                while(reader.Read()){
                    Console.WriteLine("hello");
                }
                reader.Close();
                 */
            }
            catch (SqlCeException se)
            {
                MessageBox.Show("operatingDbCS : ", se.Message);
            }
            /*
            try
            {
            configConn = Utils.createSqlConnection("configDbCS");
            }
            catch (SqlException se)
            {
            MessageBox.Show("configDbCS : ", se.Message);
            }

            try
            {
            masterConn = Utils.createSqlConnection("masterDbCS");
            }
            catch (SqlException se)
            {
            MessageBox.Show("masterDbCS : ", se.Message);
            }

            try
            {
            transConn = Utils.createSqlConnection("tranDbCS");
            }
            catch (SqlException se)
            {
            MessageBox.Show("tranDbCS : ", se.Message);
            }
            */
            try
            {
                proConn = Utils.createSqlConnection("productionDbCS");
                transConn = Utils.createSqlConnection("productionDbCS");
                masterConn = Utils.createSqlConnection("productionDbCS");
                configConn = Utils.createSqlConnection("productionDbCS");
            }
            catch (SqlException se)
            {
                MessageBox.Show("productionDbCS : ", se.Message);
            }

            //mod: change config by move every table alias
            //transConn  = masterConn = configConn = proConn;

            /*
            try
            {
                accessConnEMASTER = new OleDbConnection(strAccessConnEMASTER);
                accessConnEMASTER.Open();
            }
            catch (Exception ex)
            {
                MessageBox.Show("Error: Failed to create e-master connection. \n{0}", ex.Message);

            }

            try
            {
                accessConnBELMASTER = new OleDbConnection(strAccessConnBELMASTER);
                accessConnBELMASTER.Open();
            }
            catch (Exception ex)
            {
                MessageBox.Show("Error: Failed to create e-master connection. \n{0}", ex.Message);

            }
            try
            {
                accessConnMGMASTER = new OleDbConnection(strAccessConnMGMASTER);
                accessConnMGMASTER.Open();
            }
            catch (Exception ex)
            {
                MessageBox.Show("Error: Failed to create e-master connection. \n{0}", ex.Message);

            }
            try
            {
                accessConnVMASTER = new OleDbConnection(strAccessConnVMASTER);
                accessConnVMASTER.Open();
            }
            catch (Exception ex)
            {
                MessageBox.Show("Error: Failed to create e-master connection. \n{0}", ex.Message);

            }*/

        }

        private void testDB()
        {
            /*
            string server = Utils.getSetting("dbServer");
            string user = Utils.getSetting("dbUser");
            string passwd = Utils.getSetting("dbPassword");
            string dbName = Utils.getSetting("dbName");

            var connectionString = "Data Source=" + server + ";User ID=" + user + ";Password=" + passwd + "; Initial Catalog=" + dbName;
            Console.WriteLine("cs = {0}", connectionString);
            SqlConnection sqlConnection = new SqlConnection(connectionString);

            SqlCommand catCMD = sqlConnection.CreateCommand();
            catCMD.CommandText = "SELECT count(*) as c FROM [V-MAS-3]";

            sqlConnection.Open();

            reader = catCMD.ExecuteReader();

            while (reader.Read())
            {
                Console.WriteLine("{0}", reader["c"]);
            }
             reader.Close();
             */
        }


        private void MenuItem_Click(object sender, RoutedEventArgs e)
        {
            Settings w = new Settings();
            w.Show();
        }


        private void closeWindows(object sender, EventArgs e)
        {
            //sqlConnection.Close();
            //_aThread.Join();
            // comport.Close();

            //_clearThread = true;
            //_debugWindow.Close();
            //_bThread.Abort();
            //dw.Close();
        }


        private void button1_Click(object sender, RoutedEventArgs e)
        {
            testDB();

        }
        private bool isAlreadyCheck(string ln)
        {
            SqlCommand catCMD = proConn.CreateCommand();

            string sql = @"SELECT  * FROM lot_summary where lot_no = '" + ln + "'";
            catCMD.CommandText = sql;

            SqlDataReader reader = catCMD.ExecuteReader();

            bool r = reader.HasRows;

            reader.Close();
            return r;
        }
        private void find_Click(object sender, RoutedEventArgs e)
        {
            string ln = lotNo.Text;
            _startUsing = DateTime.Now;
            bool isFound = false;
            isMiddle = _isIn = false;
            _isExisting = false;
            _isCheck = false;
            _isTkx = false;
            midGS = "";
            inStarGS = "";
            measureGrid.ItemsSource = null;
            measureGrid.Items.Clear();
            nextCol = 3;
            middleText.Text = "Add Middle";
            inText.Text = "Add IN*";
            foreach (var view in masViews)
            {
                isFound = fillProData(ln, view);
                if (isFound == true)
                    break;

            }
            if (isFound == false)
            {
                MessageBox.Show("Lot No.:" + ln + " Not Founded");
                return;
            }



            mps = new ObservableCollection<MeasurePoint>();
            list = GetRecordType(ln);
            if (list.Count == 0)
            {
                list.Add("OUT");
                list.Add("IN");
                point1Label.Content = "OUT";
                point2Label.Content = "IN";

            }
            if (isAlreadyCheck(ln))
            {
                //ChooseRecord cr = new ChooseRecord(ln);
                //cr.ShowDialog();
                _isCheck = true;
                ChooseRecord2 cr = new ChooseRecord2(ln);
                cr.ShowDialog();

                SqlDataReader reader = Utils.Query(proConn, "select * from data where lot_no = '" + ln + "' and updated_at = '" + this._updated_at + "' order by id");
                isMiddle = false;
                _haveMiddle = false;
                while (reader.Read())
                {
                    var mp = new MeasurePoint();
                    nextCol = Convert.ToInt32(reader["ndata"]);
                    mp.Count = Convert.ToInt16(reader["row_no"]);
                    mp.Type = reader["r_type"].ToString();
                    if (mp.Type == "MID")
                    {
                        isMiddle = true;
                        _haveMiddle = true;
                        middleText.Text = "Remove Middle";
                    }

                    mp.SubOrder = Convert.ToInt16(reader["sub_order"]);
                    mp.P1 = Math.Round(Convert.ToDouble(reader["p1"]), 2);
                    mp.P2 = Math.Round(Convert.ToDouble(reader["p2"]), 2);
                    mp.P3 = Math.Round(Convert.ToDouble(reader["p3"]), 2);
                    mp.P4 = Math.Round(Convert.ToDouble(reader["p4"]), 2);
                    mp.P5 = Math.Round(Convert.ToDouble(reader["p5"]), 2);
                    mp.P6 = Math.Round(Convert.ToDouble(reader["p6"]), 2);
                    mp.P7 = Math.Round(Convert.ToDouble(reader["p7"]), 2);
                    mp.P8 = Math.Round(Convert.ToDouble(reader["p8"]), 2);
                    mp.P9 = Math.Round(Convert.ToDouble(reader["p9"]), 2);
                    mp.P10 = Math.Round(Convert.ToDouble(reader["p10"]), 2);
                    mp.Avg = Math.Round(Convert.ToDouble(reader["avg"]), 2);
                    mp.Grade = reader["grade"].ToString();
                    mp.ResultGrade = reader["rgrade"].ToString();
                    mp.Type = reader["r_type"].ToString();

                    mps.Add(mp);

                    // if row['sub_order'] == 1 and not have middle 
                    //add dummy mid row
                    //if (Convert.ToInt32(reader["sub_order"]) == 1 && _haveMiddle == false)
                    //	mps.Add(new MeasurePoint() { Count = mp.Count, Type = "MID", SubOrder = 2 });

                }
                reader.Close();
            }
            else
            {

                for (int i = 0; i < 3; i++)
                {


                    int count = 1;
                    foreach (var l in list)
                    {
                        mps.Add(new MeasurePoint() { Count = i + 1, Type = l, SubOrder = count });
                        count++;
                    }

                }
                if (_isTkx == true)
                {
                    measureGrid.Columns.ElementAt(nextCol--).Visibility = Visibility.Hidden;
                }
            }

            measureGrid.ItemsSource = mps;

            for (int i = 1; i < 10; i++)
            {
                measureGrid.Columns.ElementAt(i).Visibility = Visibility.Hidden;
            }
            for (int i = 1; i <= nextCol; i++)
            {
                measureGrid.Columns.ElementAt(i).Visibility = Visibility.Visible;
            }

            measureGrid.Focus();
            try
            {
                measureGrid.SelectedItem = measureGrid.Items[0];
                measureGrid.CurrentCell = new DataGridCellInfo(
                            measureGrid.Items[0], measureGrid.Columns[1]);
                measureGrid.BeginEdit();
            }
            catch { }
        }
        private string getConditionRef(string id)
        {
            if (string.IsNullOrEmpty(id))
            {   
                return "None";
            }
            SqlCommand cmd = configConn.CreateCommand();
            string sql = $"select * from [TABLE_TI-T4] t4 where t4.TIT4 = '{id}'";
            cmd.CommandText = sql;
            Console.WriteLine(sql);
            SqlDataReader reader = cmd.ExecuteReader();

            string condition = "";
            while (reader.Read())
            {
                condition = reader["TIT4NE"].ToString();
            }

            reader.Close();
            return condition;
        }
        private bool fillProData(string ln, string viewName)
        {

            /*
              join [V-MAS-3] v
              on p.PRO1 = v.TC
              left outer join [TABLE_TI-T4] t4 
              on v.MI5 = t4.TIT4
     
             */
            string sql = @"
            SELECT  * FROM " + viewName + " p " +
              "where p.PRO2 = '" + ln + "'";

            SqlDataReader reader = Utils.Query(proConn, sql);

            string pro1 = "";
            if (!reader.HasRows)
            {
                reader.Close();
                return false;
            }

            while (reader.Read())
            {

                string[] t = reader["MC20"].ToString().Split('/');
                string mc24 = reader["MC24"].ToString();
                string kind = reader["PRO17"].ToString();
                int gainSize;
                try
                {
                    gainSize = Convert.ToInt32(t[0]);
                }
                catch (FormatException fe)
                {
                    gainSize = 0;
                }


                if (gainSize >= 10 && gainSize <= 100 && kind == "V")
                    header = "OB";

                if (gainSize >= 120 && gainSize <= 220 && kind == "V")
                    header = "OC";

                if (gainSize >= 10 && gainSize <= 100 && mc24 == "MG")
                    header = "OB";

                if (gainSize >= 10 && gainSize <= 100 && kind == "B")
                    header = "OB";

                if (gainSize > 220 && kind == "V")
                    header = "RH";
                if (gainSize > 120 && kind == "B")
                    header = "RH";
                if (headerLabel.Content != header)
                {
                    MessageBox.Show("Please Change Using Header to '" + header + "'");
                }
                headerLabel.Content = header;

                UsingTimeTB.Text = getUsingTime(header).ToString();

                Console.WriteLine("{0}", reader["PRO2"]);
                string codeString = reader["PRO1"].ToString();
                string temp2 = codeString[0] + "-" + codeString.Substring(1, 4) + "-" + codeString.Substring(5, 4) + "-" + codeString.Substring(9, 1);
                code.Text = temp2;
                pro1 = reader["PRO1"].ToString();
                customer.Text = reader["PRO1C"].ToString();
               
                if (customer.Text.Trim().ToLower().StartsWith("tkx"))
                {
                    _isTkx = true;
                }
                noProduct.Text = reader["PRO5"].ToString();
                shape.Text = reader["PRO8"] + " " + reader["PRO9"];
                size.Text = reader["PRO10"] + "x" + reader["PRO11"] + "x" + reader["PRO12"];
                spec.Text = reader["PRO13"] + " " + reader["PRO14"] + " " + reader["PRO15"] + " " + reader["PRO16"]
                            + " " + reader["PRO17"] + " " + reader["PRO18"];
                kind = reader["PRO17"] as string;

                int mi13 = Convert.ToInt32(reader["MI13"]);
                string samplingText = "";
                if (mi13 == 1)
                {
                    samplingText = "All";
                }
                else if (mi13 == 2)
                {
                    samplingText = "2 Pcs";
                }
                else if (mi13 == 3)
                {
                    samplingText = "3 Pcs";
                }
                else if (mi13 == 4 || mi13 == 5)
                {
                    samplingText = "5 Pcs";
                }
                sampling.Text = samplingText;
                double mi18 = Convert.ToDouble(reader["MI18"]);
                double mi19 = Convert.ToDouble(reader["MI19"]);
                //Console.WriteLine(mi18);
                double o1, o2;
                if (mi18 < mi19)
                {
                    o1 = mi18;
                    o2 = mi19;
                }
                else
                {
                    o1 = mi19;
                    o2 = mi18;
                }

                this.out0 = Math.Round(o1, 2);
                this.out1 = Math.Round(o2, 2);

                var mi16 = reader["MI16"].ToString();
                sMi16 = reader["MI16"].ToString();
                sMi16 = sMi16.Replace("\\", "");
                Console.WriteLine("mi16 = " + sMi16);
                //sMi20 = sMi20.Replace("\\", "");
                var mi17 = reader["MI17"].ToString();
                if (string.IsNullOrEmpty(mi17) || mi17 == "NULL")
                {
                    mi17 = "None";
                }
                string temp = String.Format("{0:f} - {1:f} ({2}) {3}", o1, o2, mi16, mi17);
                outTB.Text = temp;
                _lower1 = o1;
                _upper1 = o2;
                double mi22 = Convert.ToDouble(reader["MI22"]);
                double mi23 = Convert.ToDouble(reader["MI23"]);

                var mi20 = reader["MI20"].ToString();
                sMi20 = reader["MI20"].ToString();

                sMi20 = sMi20.Replace("\\", "");

                string mi21 = reader["MI21"].ToString();
                if (string.IsNullOrEmpty(mi21) || mi21 == "NULL")
                {
                    mi21 = "None";
                }
                //Console.WriteLine(mi18);
                if (mi22 < mi23)
                {
                    o1 = mi22;
                    o2 = mi23;
                }
                else
                {
                    o1 = mi23;
                    o2 = mi22;
                }

                this.in0 = Math.Round(o1, 2);
                this.in1 = Math.Round(o2, 2);

                _lower2 = o1;
                _upper2 = o2;
                temp = String.Format("{0:f} - {1:f} ({2}) {3} ", o1, o2, mi20, mi21);
                inTB.Text = temp;
                point.Text = getConditionRef(reader["MI14"].ToString());
                condition.Text = getConditionRef(reader["MI15"].ToString());
                this.obCondition = reader["ob_condition"].ToString();
            }

            reader.Close();
            reader = initAgreementList(ln, viewName, reader);
            return true;
            //return pro1;
        }

        private SqlDataReader initAgreementList(string ln, string viewName, SqlDataReader reader)
        {
            var sql2 = string.Format(@"select * from (
						select MI53 as ag, PRO2 from {0}
						union
						select MI55 as ag, PRO2 from {0}
						union
						select MI31 as ag, PRO2 from {0} 
						union 
						select MI33 as ag,  PRO2 from {0} 
						union 
						select INSAGM as ag, PRO2 from {0}
						union 
						select MARAGM as ag, PRO2 from {0}
						)x WHERE PRO2 = '{1}'", viewName, ln);
            reader = Utils.Query(proConn, sql2);
            //bool isHaveAgreement = false;
            agreementCB.Items.Clear();
            bool isHaveAgreement = false;
            while (reader.Read())
            {

                //_agreementList.Add(reader["ag"].ToString());
                var temp = reader["ag"].ToString();
                //agreementCB.Text = "hello";
                if (String.IsNullOrEmpty(temp) || temp == "NULL")
                    continue;
                isHaveAgreement = true;
                var list = temp.Split(new char[] { '/', ',', '\\' });
                if (list.Length > 1)
                {
                    foreach (var l in list)
                    {
                        if (l.Trim() != "")
                        {
                            agreementCB.Items.Add(new ComboBoxItem() { Content = l });
                        }
                    }
                }
                else
                    agreementCB.Items.Add(new ComboBoxItem() { Content = temp });
            }
            if (isHaveAgreement == true)
            {
                agreementBtn.IsEnabled = true;
                agreementCB.IsEnabled = true;
                agreementCB.SelectedIndex = 0;
            }
            else
            {
                agreementBtn.IsEnabled = false;
                agreementCB.IsEnabled = false;
            }
            reader.Close();
            return reader;
        }

        private int getUsingTime(string header)
        {
            var reader = Utils.Query(_opConn, "select * from UsingTime");
            reader.Read();
            int v = 0;
            switch (header)
            {
                case "OB":
                    v = Convert.ToInt32(reader["ob"]);
                    _obCount = v;
                    _obLimit = Convert.ToInt32(reader["ob_limit"]);

                    break;
                case "OC":
                    v = Convert.ToInt32(reader["oc"]);
                    _ocCount = v;
                    _ocLimit = Convert.ToInt32(reader["oc_limit"]);
                    break;
                case "RH":
                    v = Convert.ToInt32(reader["rh"]);
                    _rhCount = v;
                    _rhLimit = Convert.ToInt32(reader["rh_limit"]);
                    break;
                default:
                    MessageBox.Show("Bad Header Name");
                    break;
            }
            reader.Close();


            return v;
        }


        /*
        private void lotNo_TextChanged(object sender, TextChangedEventArgs e)
        {
            //var s = lotNo.Text;
            //if(lotNo.Text.IndexOf('\n') != -1)
            //	find_Click(null, null);
			
        }*/

        private void openScreenKB(object sender, RoutedEventArgs e)
        {
            Console.WriteLine("Open KB");
        }

        private void lotNo_MouseDoubleClick(object sender, MouseButtonEventArgs e)
        {

        }

        private void openScreenKB(object sender, MouseButtonEventArgs e)
        {
            string windir = Environment.GetEnvironmentVariable("WINDIR");
            string osk = null;

            if (osk == null)
            {
                osk = System.IO.Path.Combine(System.IO.Path.Combine(windir, "sysnative"), "osk.exe");
                if (!File.Exists(osk))
                {
                    osk = null;
                }
            }

            if (osk == null)
            {
                osk = System.IO.Path.Combine(System.IO.Path.Combine(windir, "system32"), "osk.exe");
                if (!File.Exists(osk))
                {
                    osk = null;
                }
            }

            if (osk == null)
            {
                osk = "osk.exe";
            }

            Process.Start(osk);
        }

        private void addRow_Click(object sender, RoutedEventArgs e)
        {
            if (measureGrid.ItemsSource == null)
                return;
            _lastAction.Push("row");
            MeasurePoint m = mps.Last();

            int count = 1;
            foreach (var l in list)
            {
                mps.Add(new MeasurePoint() { Count = m.Count + 1, Type = l, SubOrder = count });
                count++;
            }

        }

        private void addMeasureColumn_Click(object sender, RoutedEventArgs e)
        {
            _lastAction.Push("column");
            if (nextCol <= 10)
            {
                measureGrid.Columns.ElementAt(++nextCol).Visibility = Visibility.Visible;

                foreach (var item in measureGrid.Items)
                {
                    //Console.WriteLine(item);
                    MeasurePoint c = item as MeasurePoint;

                    c.Avg = (c.P1 + c.P2 + c.P3 + c.P4 + c.P6 + c.P7 + c.P8 + c.P9 + c.P10) / nextCol;
                    c.Avg = Math.Round(c.Avg, 2);

                    if (c.SubOrder == 1)
                    {
                        c.Grade = computeGrade(sMi16, c.Avg, kind, "-", c.Type);
                    }
                    else if (c.SubOrder != 1 && c.Type != "MID" && c.Type != "IN*")
                    {
                        if (sMi20 != "0")
                            c.Grade = computeGrade(sMi20, c.Avg, kind, "-", c.Type);
                        else
                            c.Grade = computeGrade(sMi16, c.Avg, kind, "-", c.Type);
                    }
                }

                measureGrid.Items.Refresh();
            }
        }

        private string computeGrade(string size, double lower, string kind, string defValue, string type)
        {
            SqlCommand cmd = configConn.CreateCommand();
            if (type == "MID")
            {
                size = midGS;
            }
            else if (type == "IN*")
            {
                size = inStarGS;
            }
            int lotKind = 0;
            if (code.Text[0] == '1' || code.Text[0] == '2' || code.Text[0] == '9')
            {
                lotKind = 1;
            }
            else if (code.Text[0] == '3' || code.Text[0] == '4' || code.Text[0] == '5')
            {
                lotKind = 2;
            }



            if (double.IsNaN(lower))
            {
                lower = 0;
            }
            string sql = "";
            SqlDataReader reader;
            string value;
            if (lotKind == 1)
            {
                
                 sql = string.Format(@"SELECT * FROM [TABLE_TI-T3]  WHERE (TIT3R1 <= '{0}') AND (TIT3R2 >= '{0}') AND (round(TIT3U,2) <= '{1}') AND (round(TIT3D,2) >= '{2}')", size, lower, lower);
                cmd.CommandText = sql;
                reader = cmd.ExecuteReader();
                value = defValue;

                Console.WriteLine(sql);

                while (reader.Read())
                {

                    value = reader["TIT3G"].ToString();
                    break;
                }
                reader.Close();
                return value;
            }
            else if (lotKind == 2)
            {
                
                    sql = string.Format(@"SELECT * FROM [TABLE_TI-T3]  WHERE (TIT3R1 <= '{0}') AND (TIT3R2 >= '{0}') AND (round(TIT3U,2) <= '{1}') AND (round(TIT3D,2) >= '{2}')", size, lower, lower);
                cmd.CommandText = sql;
                Console.WriteLine(sql);
                //reader.Close();
                reader = cmd.ExecuteReader();
                value = defValue;
                while (reader.Read())
                {

                    value = reader["TIT3G"].ToString();
                    break;
                }
                reader.Close();
                return value;
            }
            else
            {
                return "-";
            }

            //return value;
        }
        //int row;




        private void measureGrid_RowEditEnding(object sender, DataGridRowEditEndingEventArgs e)
        {
            //MessageBox.Show("refresh");
            int row = e.Row.GetIndex();
            (sender as DataGrid).RowEditEnding -= measureGrid_RowEditEnding;
            (sender as DataGrid).CommitEdit();

            var c = mps[row];
            computeValues(c, true);
            measureGrid.Items.Refresh();
            (sender as DataGrid).RowEditEnding += measureGrid_RowEditEnding;
        }

        private void computeValues(MeasurePoint c, bool isCompGrade = false)
        {
            c.Avg = (c.P1 + c.P2 + c.P3 + c.P4 + c.P5 + c.P6 + c.P7 + c.P8 + c.P9 + c.P10) / nextCol;
            c.Avg = Math.Round(c.Avg, 2);

            if (isCompGrade == true)
            {
                if (c.SubOrder == 1)
                {
                    c.Grade = computeGrade(sMi16, c.Avg, kind, "-", c.Type);
                }
                else if (c.SubOrder != 1 && c.Type != "MID" && c.Type != "IN*")
                {
                    if (sMi20 != "0")
                        c.Grade = computeGrade(sMi20, c.Avg, kind, "-", c.Type);
                    else
                        c.Grade = computeGrade(sMi16, c.Avg, kind, "-", c.Type);
                }
                else if (c.Type == "MID" || c.Type == "IN*")
                {
                    c.Grade = computeGrade("0", c.Avg, kind, "-", c.Type);
                }
            }
            if (c.SubOrder == 1 || c.Type == "IN*" || c.Type == "MID" || c.Type == "FA1" || c.Type == "FA2")
            {
                if (this.header == "OB" || this.header == "OC")
                {
                    if (c.Avg >= this.out0 && c.Avg <= this.out1)
                    {
                        c.ResultGrade = "OK";
                    }
                    else if (c.Avg < this.out0)
                    {
                        c.ResultGrade = "Hard";
                    }
                    else if (c.Avg > this.out1)
                    {
                        c.ResultGrade = "Soft";
                    }
                }
                else
                {
                    if (c.Avg >= this.out0 && c.Avg <= this.out1)
                    {
                        c.ResultGrade = "OK";
                    }
                    else if (c.Avg < this.out0)
                    {
                        c.ResultGrade = "Soft";
                    }
                    else if (c.Avg > this.out1)
                    {
                        c.ResultGrade = "Hard";
                    }
                }

            }
            else if (c.SubOrder != 1)
            {
                if (this.header == "OB" || this.header == "OC")
                {
                    if (c.Avg >= this.in0 && c.Avg <= this.in1)
                    {
                        c.ResultGrade = "OK";
                    }
                    else if (c.Avg < this.in0)
                    {
                        c.ResultGrade = "Hard";
                    }
                    else if (c.Avg > this.in1)
                    {
                        c.ResultGrade = "Soft";
                    }
                }
                else
                {
                    if (c.Avg >= this.in0 && c.Avg <= this.in1)
                    {
                        c.ResultGrade = "OK";
                    }
                    else if (c.Avg < this.in0)
                    {
                        c.ResultGrade = "Soft";
                    }
                    else if (c.Avg > this.in1)
                    {
                        c.ResultGrade = "Hard";
                    }
                }
            }
        }

        private void measureGrid_KeyUp(object sender, KeyEventArgs e)
        {
            Console.WriteLine("hello");
            //MessageBox.Show(e.Key.ToString());
            var info = measureGrid.CurrentColumn;
            var item = measureGrid.CurrentItem as MeasurePoint;
            int col = info.DisplayIndex;
            var mp = (MeasurePoint)measureGrid.CurrentItem;
            int row = mps.IndexOf(mp);
            if (e.Key == Key.Tab)
            {

                //measureGrid.RaiseEvent(new RoutedEventArgs(DataGrid.rowediten));
                //MessageBox.Show("row " + item.Count.ToString());

                //MessageBox.Show("row " +  mps.IndexOf(mp).ToString());
                //MessageBox.Show("col " + info.DisplayIndex.ToString());

                if (col < nextCol)
                {
                    measureGrid.CurrentCell = new DataGridCellInfo(
                        measureGrid.Items[row], measureGrid.Columns[col + 1]);
                    measureGrid.BeginEdit();
                }
                else
                {
                    try
                    {
                        measureGrid.CurrentCell = new DataGridCellInfo(
                    measureGrid.Items[row + 1], measureGrid.Columns[1]);
                        measureGrid.BeginEdit();


                    }
                    catch
                    {
                        measureGrid.CurrentCell = new DataGridCellInfo(
                        measureGrid.Items[0], measureGrid.Columns[1]);
                        measureGrid.BeginEdit();
                    }

                }
            }
            if (e.Key == Key.Return)
            {
                if (isMiddle == false)
                    row += 2;
                if (row > measureGrid.Items.Count)
                {
                    measureGrid.CurrentCell = new DataGridCellInfo(
                        measureGrid.Items[0], measureGrid.Columns[1]);
                    measureGrid.BeginEdit();
                }
            }
        }


        private void measureGrid_CellEditEnding(object sender, DataGridCellEditEndingEventArgs e)
        {
            /*
            row = e.Row.GetIndex();
            (sender as DataGrid).CellEditEnding -= measureGrid_CellEditEnding;
            (sender as DataGrid).CommitEdit();
            var c = mps[row];
            c.Avg = (c.P1 + c.P2 + c.P3 + c.P4 + c.P6 + c.P7 + c.P8 + c.P9 + c.P10) / (nextCol - 1);
            c.Grade = computeGrade(sMi16, c.Avg, kind, "-"); 
            (sender as DataGrid).CellEditEnding += measureGrid_CellEditEnding;
            */
        }

        private void measureGrid_LostFocus(object sender, RoutedEventArgs e)
        {
            /*
            measureGrid.LostFocus -= measureGrid_LostFocus;
            measureGrid.Items.Refresh();
            measureGrid.LostFocus += measureGrid_LostFocus;
            */
        }

        private void measureGrid_LostKeyboardFocus(object sender, KeyboardFocusChangedEventArgs e)
        {
            //measureGrid.Items.Refresh();
        }

        private void commitBtn_Click(object sender, RoutedEventArgs e)
        {
            if (measureGrid.ItemsSource == null)
                return;
            var now = DateTime.Now;


            var id = Utils.getSetting("currentMachine");
            double sum = 0;
            int count = 0;
            List<List<float>> s = new List<List<float>>();
            _isExisting = true;

            Dictionary<string, List<double>> sumType = new Dictionary<string, List<double>>();

            foreach (var item in measureGrid.Items)
            {
                //Console.WriteLine(item);

                MeasurePoint mp = item as MeasurePoint;
                if (mp.Avg == null)
                {
                    mp.Avg = 0;
                }
                if (mp.Avg == 0)
                    continue;
                if (mp.Grade == null)
                {
                    mp.Grade = "-";
                }
                if (mp.ResultGrade == null)
                {
                    mp.ResultGrade = "-";
                }
                /*
                if (mp.Type == "MID" && this.isMiddle == false)
                    continue;
                if (mp.Type == "IN*" && _isIn == false)
                    continue;
                */
                if (sumType.ContainsKey(mp.Type.Trim()) == false)
                {
                    sumType[mp.Type.Trim()] = new List<double>();
                }
                (sumType[mp.Type.Trim()] as List<double>).Add(mp.Avg);

                try
                {
                    string sql = string.Format(" insert into data(lot_no, p1, p2, p3, p4, p5, p6, p7, p8, p9, p10, row_no, avg, grade, rgrade, r_type, created_at, updated_at, ndata, sub_order, machine_id, code, header) " +
                    " values ('{0}', {1}, {2}, {3}, {4}, {5}, {6}, {7}, {8}, {9}, {10}, {11}, {12}, '{13}', '{14}', '{15}', '{16}', '{17}', {18}, {19}, {20}, '{21}', '{22}' )"
                    , lotNo.Text.Trim(), mp.P1, mp.P2, mp.P3, mp.P4, mp.P5, mp.P6, mp.P7, mp.P8, mp.P9, mp.P10, mp.Count, mp.Avg, mp.Grade.Trim(), mp.ResultGrade.Trim(), mp.Type.Trim(), now, now, nextCol, mp.SubOrder, id, code.Text.Trim(), this.header);
                    sum += mp.Avg;
                    //var s0 = lotNo.Text.Trim();
                    /*
                    var tempList = new List<float>();
                    for(int i = 1; i < nextCol; i++){
                        tempList.Add(mp.GetValue("P"+i));
					
                    }
                    s.Add(tempList);
                    */
                    count++;

                    using (SqlCommand command = new SqlCommand(sql, proConn))
                    {
                        command.ExecuteNonQuery();

                    }
                }
                catch (Exception exc)
                {
                    MessageBox.Show("This here 1");
                }

            }
            //Math.Round(
            int i = 0;
            string[] keys = new string[sumType.Keys.Count];

            sumType.Keys.CopyTo(keys, 0);

            for (int k = 0; k < keys.Length; k++)
            {
                keys[k] = "'" + keys[k] + "'";
            }
            //List<string> avgValues = new List<string>();
            string[] values = new string[sumType.Keys.Count];
            int j = 0;
            string[] columns = new string[sumType.Keys.Count];
            string[] columnValues = new string[sumType.Keys.Count];
            foreach (var name in sumType)
            {
                var temp = name.Value as List<double>;
                double st = 0.0;
                foreach (double n in temp)
                {
                    st += n;
                }
                values[j] = Math.Round((double)(st / temp.Count), 2).ToString();
                columns[j] = "avg" + j + "_name";
                columnValues[j] = "avg" + j;
                j++;
            }
            double avg = Math.Round(sum / count, 2);

            string grade = "-";
            try
            {
                int a, b;
                //if (Convert.ToInt32(sMi16) <= Convert.ToInt32(sMi20))
                Int32.TryParse(sMi16, out a);
                Int32.TryParse(sMi20, out b);
                if (a <= b)
                {
                    grade = computeGrade(sMi16, avg, kind, "-", "OUT");
                }
                else
                {
                    if (Convert.ToInt32(sMi20) == 0)
                        grade = computeGrade(sMi16, avg, kind, "-", "OUT");
                    else
                        grade = computeGrade(sMi20, avg, kind, "-", "OUT");
                }
            }
            catch (Exception exc)
            {
                MessageBox.Show("Here 2 "+ sMi16 + " , " + sMi20);
            }
            try
            {
                string sql2 = string.Format("insert into lot_summary(lot_no, created_at, avg, code,  start_time, end_time, grade, machine_id, " + String.Join(",", columns) + "," + String.Join(",", columnValues) + ") values('{0}', '{1}', {2}, '{3}', '{4}', '{5}', '{6}', {7}, {8}, {9})",
                            lotNo.Text.Trim(), now, avg, code.Text.Trim(), _startUsing, now, grade.Trim(), id, String.Join(",", keys), String.Join(",", values
                            ));
                using (SqlCommand command = new SqlCommand(sql2, proConn))
                {
                    command.ExecuteNonQuery();
                }

                _updated_at = now.ToString();
                PrintLabel(lotNo.Text, now);
                MessageBox.Show("Commit Complete");
                lotNo.Focus();
                lotNo.SelectAll();
            }
            catch (Exception ex)
            {
                MessageBox.Show("Data Input Error "+ ex.Message);
            }
        }
        private void PrintLabel(string lotNo, DateTime dt)
        {
            string sql = string.Format("select * from data where lot_no = '{0}' and created_at = '{1}' order by id", lotNo, dt);
            SqlDataReader reader = Utils.Query(proConn, sql);
            string s = "";
            int n = 0;

            List<double> outs = new List<double>();
            List<double> ins = new List<double>();
            bool outValid = false;
            bool inValid = false;
            string inAvg = "";
            string outAvg = "";

            int row = 0;
            int nrow = 0;
            while (reader.Read())
            {
                nrow++;
                n = Convert.ToInt32(reader["ndata"]);

                string r_type = reader["r_type"].ToString();

                try
                {
                    r_type = r_type.Substring(0, 3);
                }
                catch
                {
                    ;
                }
                s += string.Format("{0,3}", r_type.ToUpper()) + " ";

                for (int i = 1; i <= n; i++)
                {
                    if (n > 3)
                    {
                        s += string.Format("{0,-3:0.00}", Convert.ToDouble(reader["p" + i])) + " ";
                    }
                    else
                    {
                        s += string.Format("{0,-3:0.00}", Convert.ToDouble(reader["p" + i])) + " ";
                    }


                    row++;
                }
                //s = s.Trim();
                var grade = reader["grade"].ToString().Trim();
                var rgrade = reader["rgrade"].ToString().Trim();

                try
                {
                    if (n >= 5)
                        rgrade = rgrade.Substring(0, 2);
                }
                catch
                {
                    ;
                }
                //if (reader["rgrade"].ToString().ToLower() != "ok")
                //{
                //	s += string.Format(" {0,-6:*0.00*}", Convert.ToDouble(reader["avg"])) + " " + string.Format("{0,-2}",grade) + " " + rgrade;

                //}
                //else
                //{
                if (n >= 5)
                {
                    s += string.Format("{0,5:0.00}", Convert.ToDouble(reader["avg"])) + " " + string.Format("{0,-2}", grade) + " " + rgrade;

                }
                else
                {
                    s += string.Format("{0,7:0.00}", Convert.ToDouble(reader["avg"])) + " " + string.Format("{0,-2}", grade) + " " + rgrade;

                }


                //}

                //s = s.Trim();
                s += "\n";

                /*
                UPP,UPPE = Out
                LOW,LOWE = In
                Rim = Out
                Base =In
                Soko = In
                IN* = In
                 */
                if (r_type.ToUpper() == "OUT" || r_type.ToUpper() == "TOP" || r_type.ToUpper() == "FA1" || r_type.ToUpper() == "UPP" || r_type.ToUpper() == "UPPE" || r_type.ToUpper() == "RIM")
                {

                    outs.Add(Convert.ToDouble(reader["avg"]));

                }
                if (r_type.ToUpper() == "IN" || r_type.ToUpper() == "UNDER" || r_type.ToUpper() == "FA2" || r_type.ToUpper() == "UND" || r_type.ToUpper() == "LOW" || r_type.ToUpper() == "LOWE" || r_type.ToUpper() == "BASE" || r_type.ToUpper() == "SOKO" || r_type.ToUpper() == "IN*")
                {

                    ins.Add(Convert.ToDouble(reader["avg"]));

                }

            }

            //string avg = string.Format("{0.00}", Convert.ToDouble(reader["avg"]));


            double[] inArray = new double[] { 
                                              0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
                                              0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
                                              0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
            double[] outArray = new double[] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
                                               0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
                                               0, 0, 0, 0, 0, 0, 0, 0, 0, 0};

            double sumIns = 0;
            double sumOuts = 0;

            for (int i = 0; i < ins.Count; i++)
            {
                inArray[i] = ins[i];
                sumIns += ins[i];
            }

            for (int i = 0; i < outs.Count; i++)
            {
                outArray[i] = outs[i];
                sumOuts += outs[i];
            }
            double avgIns = 0;
            if (ins.Count == 0)
                avgIns = 0;
            else
                avgIns = sumIns / ins.Count;

            double avgOut = 0;
            if (outs.Count == 0)
                avgOut = 0;
            else
                avgOut = sumOuts / outs.Count;

            reader.Close();

            sql = string.Format("select m.name , ls.avg, ls.grade, ls.start_time, ls.end_time, ls.code  from lot_summary ls, machines m where ls.lot_no = '{0}' and ls.created_at = '{1}' and ls.machine_id = m.id", lotNo, dt);
            reader = Utils.Query(proConn, sql);

            var temp = list;


            var types = string.Join("/", temp.ToArray());

            string code = "";
            string et = "";
            while (reader.Read())
            {
                code = reader["code"].ToString();
                s += string.Format("{0} Use {1}Times {2} AVG {3:0.00} {4}\n", reader["name"].ToString(), UsingTimeTB.Text.Trim(), types, Convert.ToDouble(reader["avg"]), reader["grade"].ToString());
                var startTime = Convert.ToDateTime(reader["start_time"]);
                var endTime = Convert.ToDateTime(reader["end_time"]);
                et = string.Format("{0:dd/MM/yyyy HH:mm:ss}", endTime);
                s += string.Format("Date:{0:dd/MM/yyyy} Time:{1:HH:mm}-{2:HH:mm}\n", startTime, startTime, endTime);
            }
            code = code.Replace("-", "");
            string tableName = "";

            try
            {
                accessConnEMASTER = new OleDbConnection(strAccessConnEMASTER);
                accessConnEMASTER.Open();
            }
            catch (Exception ex)
            {
                MessageBox.Show("Error: Failed to create e-master connection. \n{0}", ex.Message);

            }

            try
            {
                accessConnBELMASTER = new OleDbConnection(strAccessConnBELMASTER);
                accessConnBELMASTER.Open();
            }
            catch (Exception ex)
            {
                MessageBox.Show("Error: Failed to create e-master connection. \n{0}", ex.Message);

            }
            try
            {
                accessConnMGMASTER = new OleDbConnection(strAccessConnMGMASTER);
                accessConnMGMASTER.Open();
            }
            catch (Exception ex)
            {
                MessageBox.Show("Error: Failed to create e-master connection. \n{0}", ex.Message);

            }
            try
            {
                accessConnVMASTER = new OleDbConnection(strAccessConnVMASTER);
                accessConnVMASTER.Open();
            }
            catch (Exception ex)
            {
                MessageBox.Show("Error: Failed to create e-master connection. \n{0}", ex.Message);

            } 
            
            if (code[0] == '1' || code[0] == '9')
            {
                tempConn = accessConnVMASTER;
                tableName = "V-REREKI";
            }
            if (code[0] == '2')
            {
                tempConn = accessConnMGMASTER;
                tableName = "MG-REREKI";
            }

            if (code[0] == '3' || code[0] == '4')
            {
                tempConn = accessConnEMASTER;
                tableName = "E-REREKI";
            }
            if (code[0] == '5')
            {
                tempConn = accessConnBELMASTER;
                tableName = "BEL-REREKI";
            }
            OleDbCommand deleteCommand = new OleDbCommand("delete from [" + tableName + "] where RE01 = '" + code + "' and RE02 = '" + lotNo + "'", tempConn);
            deleteCommand.ExecuteNonQuery();
            //int lotCount = (int)selectCountCommand.ExecuteScalar();
            //if (lotCount == 0)
            //{

            string rereki = string.Format("insert into [" + tableName + "](RE01, RE02, RE03,RE04, [OB-O1], [OB-O2], [OB-O3], [OB-O4], [OB-O5], [OB-O6], [OB-O7], [OB-O8],[OB-O9], [OB-O10], [OB-O11], [OB-O12], [OB-O13], [OB-O14], [OB-O15],[OB-O16], [OB-O17], [OB-O18], [OB-O19], [OB-O20], [OB-O21], [OB-O22], [OB-O23], [OB-O24], [OB-O25],[OB-O26], [OB-O27],[OB-O28],[OB-O29],[OB-O30], [OB-I1], [OB-I2], [OB-I3], [OB-I4], [OB-I5], [OB-I6], [OB-I7], [OB-I8], [OB-I9], [OB-I10], [OB-I11], [OB-I12], [OB-I13], [OB-I14], [OB-I15], [OB-I16], [OB-I17], [OB-I18], [OB-I19], [OB-I20], [OB-I21], [OB-I22], [OB-I23], [OB-I24], [OB-I25], [OB-I26], [OB-I27], [OB-I28], [OB-I29], [OB-I30], [OB-O], [OB-I])"
                           + "values('{0}', '{1}', '{2}', {3}, {4}, {5}, {6}, {7}, {8}, {9}, {10}, {11}, {12},{13}, {14}, {15},{16}, {17}, {18},{19},{20},{21},{22}, {23},{24}, {25}, {26}, {27}, {28},{29},{30},{31},{32},{33},{34},{35},{36}, {37},{38}, {39},{40}, {41},{42},{43},{44},{45},{46},{47},{48}, {49},{50}, {51}, {52}, {53}, {54}, {55}, {56}, {57}, {58}, {59},{60},{61},{62},{63},{64}, {65})", code, lotNo, et, nrow, outArray[0], outArray[1], outArray[2], outArray[3], outArray[4], outArray[5], outArray[6], outArray[7], outArray[8], outArray[9], outArray[10], outArray[11], outArray[12], outArray[13], outArray[14], outArray[15], outArray[16], outArray[17], outArray[18], outArray[19], outArray[20], outArray[21], outArray[22], outArray[23], outArray[24], outArray[25], outArray[26], outArray[27], outArray[28], outArray[29], inArray[0], inArray[1], inArray[2], inArray[3], inArray[4], inArray[5], inArray[6], inArray[7], inArray[8], inArray[9], inArray[10], inArray[11], inArray[12], inArray[13], inArray[14], inArray[15], inArray[16], inArray[17], inArray[18], inArray[19], inArray[20], inArray[21], inArray[22], inArray[23], inArray[24], inArray[25], inArray[26], inArray[27], inArray[28], inArray[29], avgOut, avgIns);

            OleDbCommand insertCmd = new OleDbCommand(rereki, tempConn);
            //MessageBox.Show("re = " + rereki);
            insertCmd.ExecuteNonQuery();
            //}
            accessConnBELMASTER.Close();
            accessConnEMASTER.Close();
            accessConnMGMASTER.Close();
            accessConnVMASTER.Close();

            reader.Close();
            //Utils.Query(proConn, "select P1, P2, P3, P4, P5, P6, P7, P8, P9, P10 from lot_summary where lot_no = 
            //Printer.Print(s, n);
            //Printer.Print(s);
            printMultipage(s, n);
            //var p = new Printer();

        }
        void printMultipage(string s, int n)
        {

            var lines = s.Split('\n');
            const int NL = 8;
            var el = lines.Count() / NL;
            string postFix = "";

            for (var i = 0; i < el; i++)
            {

                var pages = String.Format("Lot No. {0} {1}\n", lotNo.Text, this.obCondition);
                //pages += String.Format("Std.Wb={0:0.##}g\nStd.I-5-5={1:0.##}g\n", stdWbUI.Text, i55UI.Text);
                for (var j = 0; j < NL; j++)
                {
                    pages += lines[j + (i * NL)] + "\n";
                }
                Printer.Print(pages);
            }

            /*
            Printer p = new Printer();
            Console.WriteLine("printer print");
            p.PrintDoc(s);*/

            var remain = lines.Count() % NL;
            if (remain == 0)
                return;
            var pager = String.Format("Lot No. {0} {1}\n", lotNo.Text, this.obCondition);
            //pager += String.Format("Std.Wb={0:0.##}g\nStd.I-5-5={1:0.##}g\n", stdWbUI.Text, i55UI.Text);
            for (var j = el * NL; j < lines.Count(); j++)
            {
                if (lines[j] == "")
                    continue;
                pager += lines[j] + "\n";
            }

            Printer.Print(pager);

        }
        private void measureGrid_LoadingRow(object sender, DataGridRowEventArgs e)
        {
            /*
            DataGridRow c = e.Row;
            MeasurePoint mp = e.Row.Item as MeasurePoint;
            if (mp.Type == "MID" && this.isMiddle == false)
            {
                c.Visibility = Visibility.Collapsed;
            }
            if (mp.Type == "IN*" && _isIn == false)
            {
                c.Visibility = Visibility.Collapsed;
            }
            */
        }



        private void addMiddleBtn_Click(object sender, RoutedEventArgs e)
        {
            if (measureGrid.ItemsSource == null)
                return;
            _lastAction.Push("middle");

            this.isMiddle = !this.isMiddle;

            if (this.isMiddle == false)
            {
                middleText.Text = "Add Middle";

                RemoveMid();
            }
            else
            {
                middleText.Text = "Remove Middle";
                EditMIDWindow w = new EditMIDWindow();
                w.ShowDialog();
                AddMid();

            }
            //this.measureGrid.CommitEdit();
            measureGrid.Items.Refresh();
        }

        private void RemoveMid()
        {
            list.Remove("MID");
            ObservableCollection<MeasurePoint> temp = new ObservableCollection<MeasurePoint>();
            foreach (var m in mps)
            {

                if (m.Type != "MID")
                {
                    temp.Add(m);
                }
            }
            mps = temp;
            measureGrid.ItemsSource = null;
            measureGrid.ItemsSource = mps;
        }

        private void AddMid()
        {


            list.Insert(1, "MID");
            ObservableCollection<MeasurePoint> temp = new ObservableCollection<MeasurePoint>();
            foreach (var m in mps)
            {
                temp.Add(m);
                if (m.SubOrder == 1)
                {
                    temp.Add(new MeasurePoint() { Type = "MID", SubOrder = m.SubOrder + 1, Count = m.Count });
                }
            }
            mps = temp;
            measureGrid.ItemsSource = null;
            measureGrid.ItemsSource = mps;
        }



        private void deleteData_Click(object sender, RoutedEventArgs e)
        {
            this.currentMP.setValue(currentColumn, 0);
            this.computeValues(currentMP, true);
            measureGrid.Items.Refresh();

        }

        private void measureGrid_BeginningEdit(object sender, DataGridBeginningEditEventArgs e)
        {

            this.currentColumn = e.Column.Header.ToString();
            this.currentMP = (MeasurePoint)e.Row.Item;

            cellIndicattor.Text = "(" + currentMP.Type + "-" + currentMP.Count + ", " + currentColumn + ")";

        }

        private void measureGrid_SelectedCellsChanged(object sender, SelectedCellsChangedEventArgs e)
        {

            //this.currentMP = (MeasurePoint)measureGrid.CurrentItem;
            //this.currentColumn = measureGrid.CurrentColumn.Header.ToString();
            //cellIndicattor.Text = "("+currentMP.Type + "-" +currentMP.Count+", "+currentColumn+")";

        }

        private void measureGrid_CurrentCellChanged(object sender, EventArgs e)
        {
            try
            {
                this.currentColumn = measureGrid.CurrentColumn.Header.ToString();
                this.currentMP = (MeasurePoint)measureGrid.CurrentItem;
                cellIndicattor.Text = "(" + currentMP.Type + "-" + currentMP.Count + ", " + currentColumn + ")";

                //this.computeValues(currentMP);

            }
            catch (NullReferenceException ne) { }
        }

        private void saveCellBtn_Click(object sender, RoutedEventArgs e)
        {
            measureGrid.Focus();
            if (currentColumn == null)
                return;

            if (_isOver == true)
                return;
            /*
            if(_isFirstMeasure == true){
                _startUsing = DateTime.Now;
                _isFirstMeasure = false;
            }*/
            if (currentColumn != "Average" && currentColumn != "Grade" && currentColumn != "Result Grade")
            {
                Console.WriteLine("reading box"+readingBox.Text);
                
                this.currentMP.setValue(currentColumn, Convert.ToDouble(readingBox.Text.Replace(" ", "")));
                //var c = measureGrid.SelectedValue;

                this.computeValues(currentMP, true);

            }
            try
            {
                var info = measureGrid.CurrentColumn;
                var item = measureGrid.CurrentItem as MeasurePoint;
                int col = info.DisplayIndex;
                var mp = (MeasurePoint)measureGrid.CurrentItem;
                int row = mps.IndexOf(mp);

                //measureGrid.RaiseEvent(new RoutedEventArgs(DataGrid.rowediten));
                //MessageBox.Show("row " + item.Count.ToString());

                //MessageBox.Show("row " +  mps.IndexOf(mp).ToString());
                //MessageBox.Show("col " + info.DisplayIndex.ToString());


                measureGrid.Items.Refresh();
                measureGrid.Focus();
                if (col < nextCol)
                {
                    measureGrid.CurrentCell = new DataGridCellInfo(
                        measureGrid.Items[row], measureGrid.Columns[col + 1]);
                    measureGrid.BeginEdit();
                }
                else
                {
                    try
                    {
                        //this.computeValues(currentMP, true);
                        measureGrid.CurrentCell = new DataGridCellInfo(
                    measureGrid.Items[row + 1], measureGrid.Columns[1]);
                        measureGrid.SelectedItem = measureGrid.Items[row + 1];
                        measureGrid.BeginEdit();


                    }
                    catch
                    {
                        measureGrid.CurrentCell = new DataGridCellInfo(
                        measureGrid.Items[0], measureGrid.Columns[1]);
                        measureGrid.SelectedItem = measureGrid.Items[0];
                        measureGrid.BeginEdit();
                    }


                }
            }
            catch
            {
                ;
            }
            updateUsingTime(this.header);

        }

        private void updateUsingTime(string p, int n = -1)
        {

            switch (p)
            {
                case "OB":
                    _obCount++;
                    _usingTime = _obCount;
                    if (_obCount > _obLimit)
                    {
                        _obCount = _obLimit;
                        Alert alert = new Alert();
                        alert.SetAlertMsg("OB Header Exceeds Usage Limit");
                        alert.ShowDialog();
                        _isOver = true;
                    }
                    _isOver = false;
                    if (n == -1)
                    {
                        Utils.Query(_opConn, "update UsingTime set ob = " + _obCount);
                        UsingTimeTB.Text = _obCount.ToString();
                    }
                    else
                    {
                        Utils.Query(_opConn, "update UsingTime set ob = " + n);
                        UsingTimeTB.Text = n.ToString();
                        _obCount = n;
                    }
                    break;
                case "OC":
                    _ocCount++;
                    _usingTime = _ocCount;
                    if (_ocCount > _ocLimit)
                    {
                        _ocCount = _ocLimit;
                        Alert alert = new Alert();
                        alert.SetAlertMsg("OC Header Exceeds Usage Limit");
                        alert.ShowDialog();
                        _isOver = true;
                    }
                    _isOver = false;
                    if (n == -1)
                    {
                        Utils.Query(_opConn, "update UsingTime set oc = " + _ocCount);
                        UsingTimeTB.Text = _ocCount.ToString();
                    }
                    else
                    {
                        Utils.Query(_opConn, "update UsingTime set oc = " + n);
                        UsingTimeTB.Text = n.ToString();
                        _ocCount = n;
                    }
                    break;
                case "RH":
                    _rhCount++;
                    _usingTime = _rhCount;
                    if (_rhCount > _rhLimit)
                    {
                        _rhCount = _rhLimit;
                        Alert alert = new Alert();
                        alert.SetAlertMsg("RH Header Exceeds Usage Limit");
                        alert.ShowDialog();
                        _isOver = true;
                    }
                    _isOver = false;
                    if (n == -1)
                    {
                        Utils.Query(_opConn, "update UsingTime set rh = " + _rhCount);
                        UsingTimeTB.Text = _rhCount.ToString();
                    }
                    else
                    {
                        Utils.Query(_opConn, "update UsingTime set rh = " + n);
                        UsingTimeTB.Text = n.ToString();
                        _rhCount = n;
                    }
                    break;
                default:
                    //MessageBox.Show("Please Find a Lot NO First");
                    break;
            }
        }

        public void refreshUsingTime()
        {
            string p = this.header;

            string sql = string.Format("select  {0} as n from UsingTime", this.header.ToLower());
            var reader = Utils.Query(_opConn, sql);
            reader.Read();
            UsingTimeTB.Text = reader["n"].ToString();
            if (p == "OB")
            {
                _obCount = Convert.ToInt32(reader["n"]);
            }
            else if (p == "OC")
            {
                _ocCount = Convert.ToInt32(reader["n"]);
            }


        }
        private void IntranetBtn_Click(object sender, RoutedEventArgs e)
        {
            SqlDataReader reader = Utils.Query(proConn, "select value from sys_configs where title = 'internal_url'");

            reader.Read();
            string target = reader["value"].ToString();
            //string target = reader["value"].Read().ToString();
            try
            {
                System.Diagnostics.Process.Start(target);
            }
            catch (System.ComponentModel.Win32Exception noBrowser)
            {
                if (noBrowser.ErrorCode == -2147467259)
                    MessageBox.Show(noBrowser.Message);
            }
            catch (System.Exception other)
            {
                MessageBox.Show(other.Message);
            }
            reader.Close();
        }

        private void undoBtn_Click(object sender, RoutedEventArgs e)
        {
            if (_lastAction.Count == 0)
                return;
            string action = _lastAction.Pop();
            if (action == "middle")
            {
                this.isMiddle = !this.isMiddle;

                if (this.isMiddle == false)
                {
                    middleText.Text = "Add Middle";
                    RemoveMid();
                }
                else
                {
                    middleText.Text = "Remove Middle";
                    AddMid();
                }

            }
            if (action == "in")
            {
                _isIn = !_isIn;

                if (_isIn == false)
                {
                    inText.Text = "Add IN*";
                    RemoveIn();
                }
                else
                {
                    inText.Text = "Remove IN*";
                    AddIn();
                }

            }
            else if (action == "row")
            {
                for (int i = 0; i < list.Count; i++)
                {
                    mps.RemoveAt(mps.Count - 1);
                }
            }
            else if (action == "column")
            {

                measureGrid.Columns.ElementAt(nextCol--).Visibility = Visibility.Hidden;

                foreach (var item in measureGrid.Items)
                {
                    //Console.WriteLine(item);
                    MeasurePoint c = item as MeasurePoint;

                    c.setValue((nextCol + 1).ToString(), (float)0.0);
                    c.Avg = (c.P1 + c.P2 + c.P3 + c.P4 + c.P6 + c.P7 + c.P8 + c.P9 + c.P10) / (nextCol);
                    c.Avg = Math.Round(c.Avg, 2);
                    if (c.SubOrder == 1)
                    {
                        c.Grade = computeGrade(sMi16, c.Avg, kind, "-", c.Type);
                    }
                    else if (c.SubOrder != 1 && c.Type != "MID" && c.Type != "IN*")
                    {
                        if (sMi20 != "0")
                            c.Grade = computeGrade(sMi20, c.Avg, kind, "-", c.Type);
                        else
                            c.Grade = computeGrade(sMi16, c.Avg, kind, "-", c.Type);
                    }
                }


            }
            else if (action == "remove_column")
            {

                measureGrid.Columns.ElementAt(++nextCol).Visibility = Visibility.Visible;

                foreach (var item in measureGrid.Items)
                {
                    //Console.WriteLine(item);
                    MeasurePoint c = item as MeasurePoint;

                    c.setValue((nextCol).ToString(), (float)0.0);
                    computeValues(c, true);
                }


            }

            measureGrid.Items.Refresh();
        }

        private void printBtn_Click(object sender, RoutedEventArgs e)
        {
            if (_isExisting == true)
            {
                PrintLabel(lotNo.Text, Convert.ToDateTime(_updated_at));
            }
            else
            {
                MessageBox.Show("You can print when you have commited data");
            }

        }

        private void agreementBtn_Click(object sender, RoutedEventArgs e)
        {
            var fileName = agreementCB.Text;
            try
            {
                //System.Diagnostics.Process.Start(@"agreements\" + fileName);

                var server = Utils.getSetting("webServerURL");
                string data = string.Format(@"title={0}&empid={1}&password={2}", fileName, GlobalVars.user.empid, GlobalVars.user.password);
                WebAppConnector wp = new WebAppConnector()
                {

                    Uri = Utils.getSetting("webServerURL") + "/agreements/title.json",
                    Method = "POST",
                    PostData = data
                };
                Response r = null;
                try
                {
                    r = wp.sendRequest();
                }
                catch
                {
                    MessageBox.Show("Cannot connect to webserver :" + server);
                    return;
                }
                string ans = (string)r.jsonBody["msg"];
                //Console.WriteLine((JArray)r.jsonBody["roles"]);

                if (r.status == "OK" && ans == "y")
                {
                    System.Diagnostics.Process.Start(server + (string)r.jsonBody["url"]);
                }
                else
                {
                    MessageBox.Show("Cannot find agreement file");
                }
            }
            catch (Win32Exception ew)
            {
                MessageBox.Show(ew.Message);
            }
        }

        private void thaiMenu_Checked(object sender, RoutedEventArgs e)
        {
            engMenu.IsChecked = false;
            //var selectedItem = comboBoxLanguage.SelectedItem as ComboBoxItem;

            var culture = CultureInfo.GetCultureInfo("th-TH");

            Dispatcher.Thread.CurrentCulture = culture;
            Dispatcher.Thread.CurrentUICulture = culture;

            LocalizationManager.UpdateValues();
        }

        private void engMenu_Checked(object sender, RoutedEventArgs e)
        {
            thaiMenu.IsChecked = false;
            var culture = CultureInfo.GetCultureInfo("en-US");

            Dispatcher.Thread.CurrentCulture = culture;
            Dispatcher.Thread.CurrentUICulture = culture;

            LocalizationManager.UpdateValues();
        }



        private void windowItem_Checked(object sender, RoutedEventArgs e)
        {
            this.WindowStyle = WindowStyle.SingleBorderWindow;
            this.WindowState = WindowState.Normal;
            this.isFullScreen = false;
            fullScreenItem.IsChecked = false;
        }

        private void fullScreenItem_Checked(object sender, RoutedEventArgs e)
        {
            this.WindowStyle = WindowStyle.None;
            this.WindowState = WindowState.Maximized;
            this.isFullScreen = true;
            windowItem.IsChecked = false;
        }

        private void measureGrid_KeyDown(object sender, KeyEventArgs e)
        {
        }

        private void measureGrid_Loaded(object sender, RoutedEventArgs e)
        {
            //MessageBox.Show("Refresh Finish");
        }

        private void measureGrid_SourceUpdated(object sender, DataTransferEventArgs e)
        {
            MessageBox.Show("refresh finish");
        }

        private void measureGrid_ColumnDisplayIndexChanged(object sender, DataGridColumnEventArgs e)
        {

        }

        private void measureGrid_PreviewKeyDown(object sender, KeyEventArgs e)
        {

        }

        private void rlChick(object sender, RoutedEventArgs e)
        {
            _rlWindow = new RLWindow();
            //_dc.Show();
            _rlWindow.Show();
            //_dc.ShowDialog();
        }

        private void lotNo_MouseDown(object sender, MouseButtonEventArgs e)
        {
            //lotNo.SelectAll();	
        }

        private void lotNo_GotFocus(object sender, RoutedEventArgs e)
        {
            //lotNo.SelectAll();
        }

        private void lotNo_GotKeyboardFocus(object sender, KeyboardFocusChangedEventArgs e)
        {
            lotNo.SelectAll();
        }

        private void lotNo_GotMouseCapture(object sender, MouseEventArgs e)
        {
            lotNo.SelectAll();
        }

        private void resetBtn_Click(object sender, RoutedEventArgs e)
        {
            updateUsingTime(this.header, 0);
            measureGrid.Focus();
            try
            {
                measureGrid.CurrentCell = new DataGridCellInfo(
                            measureGrid.Items[0], measureGrid.Columns[1]);
                measureGrid.SelectedItem = measureGrid.Items[0];
                measureGrid.BeginEdit();
            }
            catch
            {
            }
        }

        private void editUsingTime_Click(object sender, RoutedEventArgs e)
        {
            EditUsingTime editUsingTime = new EditUsingTime();
            editUsingTime.ShowDialog();
        }

        private void addInBtn_Click(object sender, RoutedEventArgs e)
        {
            //measureGrid.ItemsSource  = null;
            if (measureGrid.ItemsSource == null)
                return;
            _isIn = !_isIn;

            if (_isIn == false)
            {
                inText.Text = "Add IN*";
                RemoveIn();
            }
            else
            {
                inText.Text = "Remove IN*";
                EditINWindow w = new EditINWindow();
                w.ShowDialog();
                AddIn();
            }
            //ObservableCollection<MeasurePoint> temp = new ObservableCollection<MeasurePoint>();
            _lastAction.Push("in");
            measureGrid.Items.Refresh();
            /*
            for(int i = 0; i < mps.Count; i++){	
                var mp = mps[i];
                if(mp.SubOrder == 1){
                    mps.Insert(mps.IndexOf(mp) + 1, new MeasurePoint() { Count = mp.Count, Type = "IN*", SubOrder = 3});
                }
            }
            measureGrid.ItemsSource = mps;
            */

            //measureGrid.ItemsSource = null;
            //measureGrid.Items.Add(0, new MeasurePoint() { Count = 1, Type = "In"});
        }

        private void RemoveIn()
        {
            list.Remove("IN*");
            ObservableCollection<MeasurePoint> temp = new ObservableCollection<MeasurePoint>();
            foreach (var m in mps)
            {

                if (m.Type != "IN*")
                {
                    temp.Add(m);
                }
            }
            mps = temp;
            measureGrid.ItemsSource = null;
            measureGrid.ItemsSource = mps;

        }

        private void AddIn()
        {
            list.Insert(1, "IN*");
            ObservableCollection<MeasurePoint> temp = new ObservableCollection<MeasurePoint>();
            foreach (var m in mps)
            {
                temp.Add(m);
                if (m.SubOrder == 1)
                {
                    temp.Add(new MeasurePoint() { Type = "IN*", SubOrder = m.SubOrder + 1, Count = m.Count });
                }
            }
            mps = temp;
            measureGrid.ItemsSource = null;
            measureGrid.ItemsSource = mps;
        }

        private void dailyCheckBtn_Click(object sender, RoutedEventArgs e)
        {
            _dc = new DailyCheck();
            //_dc.Show();
            _dc.ShowDialog();
            //_dc.ShowDialog();
        }

        private void removeMeasureColumn_Click(object sender, RoutedEventArgs e)
        {
            _lastAction.Push("remove_column");

            measureGrid.Columns.ElementAt(nextCol).Visibility = Visibility.Hidden;
            if (nextCol <= 10)
            {
                measureGrid.Columns.ElementAt(--nextCol).Visibility = Visibility.Visible;

                foreach (var item in measureGrid.Items)
                {
                    //Console.WriteLine(item);
                    MeasurePoint c = item as MeasurePoint;
                    c.setValue((nextCol + 1).ToString(), 0);
                    computeValues(c, true);
                }

                measureGrid.Items.Refresh();
            }
        }

        private void lotNo_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.Return)
            {
                //MessageBox.Show("Hello");
                find_Click(null, null);
            }
        }

        private void checkLogin_Click(object sender, RoutedEventArgs e)
        {
            var server = Utils.getSetting("webServerURL");
            //string data = string.Format(@"title={0}", fileName);
            WebAppConnector wp = new WebAppConnector()
            {

                Uri = Utils.getSetting("webServerURL") + "/sites/get_current_user.json",
                Method = "POST",
                PostData = ""
            };
            Response r = null;
            try
            {
                r = wp.sendRequest();
            }
            catch
            {
                MessageBox.Show("Cannot connect to webserver :" + server);
            }
            string ans = (string)r.jsonBody["u"];
            //Console.WriteLine((JArray)r.jsonBody["roles"]);
        }

        private void searchAgreementBtn_Click(object sender, RoutedEventArgs e)
        {
            SearchAgreement sa = new SearchAgreement();
            sa.ShowDialog();
        }

        private void editINStar_Click(object sender, RoutedEventArgs e)
        {
            EditINWindow w = new EditINWindow();
            w.ShowDialog();
            foreach (var item in measureGrid.Items)
            {
                MeasurePoint c = item as MeasurePoint;
                computeValues(c, true);
            }
            measureGrid.Items.Refresh();
        }

        private void editMID_Click(object sender, RoutedEventArgs e)
        {
            EditMIDWindow w = new EditMIDWindow();
            w.ShowDialog();
            foreach (var item in measureGrid.Items)
            {
                MeasurePoint c = item as MeasurePoint;
                computeValues(c, true);
            }
            measureGrid.Items.Refresh();
        }

        private void logoutMenu_Click(object sender, RoutedEventArgs e)
        {
            this.Hide();
            LoginWindow lw = new LoginWindow();
            var r = lw.ShowDialog();
            resetMenu();

        }

        private void about_Click(object sender, RoutedEventArgs e)
        {
            Window1 w = new Window1();
            w.ShowDialog();
        }

        private void Window_Closing(object sender, CancelEventArgs e)
        {
            if (comport.IsOpen)
            {
                comport.Close();
                _clearThread = true;
            }
        }







    }
}
