using System;
using System.Linq;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Runtime.InteropServices;
using System.Net.Sockets;
using System.Net;
using SCAN.Data.DataAccess;
using SCAN.Data.DataModel;
using System.Threading;
//using TowerLightSignal;
using Bt.ScanLib;
using Bt.CommLib;
using CsvReadWrite;
using Bt;
using System.Threading;
//using StateObjects;
using SCAN.lib;

namespace SCAN
{
    public partial class Form_WeightDataToPrintB : Form
    {
        public static Form_WeightDataToPrintB _Form_WeightDataToPrintBInstance;

        [System.Runtime.InteropServices.DllImport("coredll.dll")]
        static extern short GetUserDefaultUILanguage();

        public static System.Net.Sockets.TcpClient objSck;

        private NetworkStream stream;

        private Int32 remotePort;

        private string remoteHost;

        public static Socket client;

        public static Socket listener;

        public static Socket handler;

        private static ManualResetEvent connectDone = new ManualResetEvent(false);

        private static ManualResetEvent receiveDone = new ManualResetEvent(false);
        // The response from the remote device.
        private static String response = String.Empty;

        private bool IsClose = true;

        private bool IsProcess = true;

        private string wightBefore = string.Empty;

        //public static string weightData = string.Empty;

        //public static bool IsContinue = false;

        //public static bool IsCloseShare = false;


        //TowerlightSignal objTowerlight = new TowerlightSignal();

        public event ScanEventHandler OnScan;


        public Form_WeightDataToPrintB()
        {
            InitializeComponent();

        }

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

            // フォームの最大化・最小化ボタン非表示
            this.MaximizeBox = !this.MaximizeBox;
            this.MinimizeBox = !this.MinimizeBox;

            lblError.Text = string.Empty;


            String HostIP1 = Form_Login._Form_LoginInstance.SettingsIP[0][0];
            String HostIP2 = Form_Login._Form_LoginInstance.SettingsIP[0][1];
            String HostIP3 = Form_Login._Form_LoginInstance.SettingsIP[0][2];
            String HostIP4 = Form_Login._Form_LoginInstance.SettingsIP[0][3];
            String Port = Form_Login._Form_LoginInstance.SettingsIP[0][4];

            Int32 _port = 5000;
            if (Port != string.Empty)
            {
                _port = Convert.ToInt32(Port);
            }

            string _hostIp = HostIP1 + "." + HostIP2 + "." + HostIP3 + "." + HostIP4;


            //Int32 remotePort = Convert.ToInt32(_port);
            remotePort = Convert.ToInt32(_port);
            remoteHost = _hostIp;

            try
            {

                //connectPLC(_port, _hostIp);

                //MessageBox.Show(remoteHost + " | " + remotePort);

                //objSck = new System.Net.Sockets.TcpClient(remoteHost, remotePort);

                //stream = objSck.GetStream();


                //Thread receivingThread = new Thread(ReceivingMethod);
                //receivingThread.IsBackground = true;
                //receivingThread.Start();

                //var tcpClient = new TcpClient(remoteHost, remotePort);
                //tcpClient.DataReceived += OnDataReceived;

                //btnConnect.Enabled = false;

                wightBefore = string.Empty;

                IsClose = true;

                IsProcess = true;

                //bool Valid = connectPLC(remotePort, remoteHost);

                //if (Valid == false)
                //{
                //    timer1.Enabled = false;
                //    MessageBox.Show("Connection Error");
                //    //btnConnect.Enabled = true;

                //    Bluetooth.btBluetoothClose();
                //    Form_Menu._Form_MenuInstance.Show();
                //    this.Close();
                //}

                timer1.Enabled = true;


            }
            catch (Exception)
            {

                MessageBox.Show("Connection Error");


            }




        }

        #region "socket"
        private bool connectPLC(Int32 port, string ips)
        {

            //IPAddress host = IPAddress.Parse(ips);//  
            //IPEndPoint ipendpoint = new IPEndPoint(host, port); // assign host and port                                                               
            //client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);


            //IPHostEntry host1 = Dns.GetHostEntry("localhost");
            //IPAddress ipAddress = host1.AddressList[0];
            IPAddress ipAddress = IPAddress.Parse(ips);
            IPEndPoint localEndPoint = new IPEndPoint(ipAddress, port);


            try
            {
                //Byte[] sendByte = System.Text.Encoding.ASCII.GetBytes("WR EM" + "0" + ".H " + "OK" + "\r");

                // Connect to the remote endpoint.
                //client.BeginConnect(ipendpoint, new AsyncCallback(ConnectCallback), client);
                //connectDone.WaitOne();

                //client.Connect(ipendpoint);

                // Receive the response from the remote device.
                //Receive(client);
                //receiveDone.WaitOne();

                // Write the response to the console.
                //Console.WriteLine("Response received : {0}", response);

                //lblWeight.Text = response;

                // Release the socket.
                //client.Shutdown(SocketShutdown.Both);
                //client.Close();

                //btnConnect.Enabled = false;

                IsClose = false;

                //MessageBox.Show(ipAddress.ToString());

                // Create a Socket that will use Tcp protocol
                listener = new Socket(ipAddress.AddressFamily, SocketType.Stream, ProtocolType.Tcp);

                //MessageBox.Show("1");
                Thread.Sleep(50);

                // A Socket must be associated with an endpoint using the Bind method
                listener.Bind(localEndPoint);

                //MessageBox.Show("2");
                Thread.Sleep(50);

                // Specify how many requests a Socket can listen before it gives Server busy response.
                // We will listen 10 requests at a time
                listener.Listen(10);

                //MessageBox.Show("3");

                Thread.Sleep(50);

                //listener.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReceiveTimeout, 40000);


                //handlerReceive();








                //client.Connect(ipendpoint);



                //byte[] RecvBytes = new byte[100];


                //Int32 bytes = client.Receive(RecvBytes, RecvBytes.Length, 0);

                //String receiveText = Encoding.ASCII.GetString(RecvBytes, 0, bytes);

                //lblWeight.Text = receiveText;





            }
            catch (SocketException e)
            {

                //client.Close();

                IsClose = true;
                return false;
            }


            //client.Close();

            IsClose = true;
            return true;
        }
        #endregion

        private bool handlerReceive()
        {
            try
            {
                //Console.WriteLine("Waiting for a connection...");
                //lblError.BackColor = Color.Green;
                //lblError.Text = "Waiting for receive";

                //Socket handler = listener.Accept();

                handler = listener.Accept();

                
                // Incoming data from the client.
                string data = null;
                byte[] bytes = null;
                int bytesRec = 0;

                while (true)
                {
                    bytes = new byte[1024];
                    bytesRec = handler.Receive(bytes);

                    data += Encoding.ASCII.GetString(bytes, 0, bytesRec);
                    string dataWeight = string.Empty;
                    string[] strData = data.Split('+');

                    if (data.Contains("ST"))
                    {
                        dataWeight = strData[1].Trim().Replace("  ", " ").Replace("ST,GS","").Replace(",","");

                        //Form_Login.weightData = dataWeight.Substring(0, dataWeight.Length - 3);

                        lblWeight.Text = dataWeight;



                    }

                    else if (data.Contains("S") && !data.Contains("US"))
                    {
                        if (strData.Length == 2)
                        {

                            dataWeight = strData[1].Trim().Replace(" ", "");

                            dataWeight = dataWeight.Substring(0, dataWeight.Length - 1);

                            dataWeight = dataWeight.Substring(0, dataWeight.Length - 2) 
                                + " " + dataWeight.Substring(dataWeight.Length - 2, 2);

                            //Form_Login.weightData = dataWeight.Substring(0, dataWeight.Length - 3);

                        }
                        else
                        {
                            dataWeight = "";
                            Form_Login.weightData = dataWeight;
                        }

                        

                        lblWeight.Text = dataWeight;



                    }
                   

                    else
                    {
                        dataWeight = "";
                        Form_Login.weightData = dataWeight;
                        lblWeight.Text = dataWeight;

                        handler.Shutdown(SocketShutdown.Both);
                        handler.Close();
                        //IsContinue = false;
                        return true;
                    }



                    break;

                    //if (data.IndexOf("<EOF>") > -1)
                    //{
                    //    break;
                    //}
                }

                //Console.WriteLine("Text received : {0}", data);

                //byte[] msg = Encoding.ASCII.GetBytes(data);
                //handler.Send(msg);

                
                handler.Shutdown(SocketShutdown.Both);
                handler.Close();
                //IsContinue = false;
                return true;

            }
            catch (Exception)
            {
                
                handler.Shutdown(SocketShutdown.Both);
                handler.Close();
                //IsContinue = false;
                return false;

            }

        }

        private static void ConnectCallback(IAsyncResult ar)
        {
            try
            {
                // Retrieve the socket from the state object.
                Socket client = (Socket)ar.AsyncState;

                // Complete the connection.
                client.EndConnect(ar);

                //Console.WriteLine("Socket connected to {0}", client.RemoteEndPoint.ToString());

                // Signal that the connection has been made.
                connectDone.Set();
            }
            catch (Exception e)
            {
                Console.WriteLine(e.ToString());
            }
        }

        private static void Receive(Socket client)
        {
            try
            {
                // Create the state object.
                StateObject state = new StateObject();
                state.workSocket = client;

                // Begin receiving the data from the remote device.
                client.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0,
                    new AsyncCallback(ReceiveCallback), state);
            }
            catch (Exception e)
            {
                //Console.WriteLine(e.ToString());
            }
        }

        private static void ReceiveCallback(IAsyncResult ar)
        {
            try
            {
                // Retrieve the state object and the client socket 
                // from the asynchronous state object.
                StateObject state = (StateObject)ar.AsyncState;
                Socket client = state.workSocket;

                // Read data from the remote device.
                int bytesRead = client.EndReceive(ar);

                if (bytesRead > 0)
                {
                    // There might be more data, so store the data received so far.
                    state.sb.Append(Encoding.ASCII.GetString(state.buffer, 0, bytesRead));

                    // Get the rest of the data.
                    client.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0,
                        new AsyncCallback(ReceiveCallback), state);
                }
                else
                {
                    // All the data has arrived; put it in response.
                    if (state.sb.Length > 1)
                    {
                        response = state.sb.ToString();
                    }
                    // Signal that all bytes have been received.
                    receiveDone.Set();
                }
            }
            catch (Exception e)
            {
                //Console.WriteLine(e.ToString());
            }
        }

        void OnDataReceived(byte[] receivedData)
        {
            String responseData = String.Empty;

            // Read the first batch of the TcpServer response bytes.
            Int32 bytes = stream.Read(receivedData, 0, receivedData.Length); //(**This receives the data using the byte method**)
            responseData = System.Text.Encoding.ASCII.GetString(receivedData, 0, bytes); //(**This converts it to string**)

            Form_Login.weightData = responseData;

            lblWeight.Text = responseData;
        }


        private void ReceivingMethod()
        {
            while (true)
            {
                try
                {
                    //MessageBox.Show(objSck.Client.Available.ToString());

                    Byte[] sendByte = System.Text.Encoding.ASCII.GetBytes("WR EM" + "" + ".H " + "" + "\r");

                    stream.Write(sendByte, 0, sendByte.Length);

                    if (objSck.Client.Available > 0)
                    {
                        //------------Receive-----------
                        // Buffer to store the response bytes.
                        Byte[] data = new Byte[256];

                        // String to store the response ASCII representation.
                        String responseData = String.Empty;

                        // Read the first batch of the TcpServer response bytes.
                        Int32 bytes = stream.Read(data, 0, data.Length); //(**This receives the data using the byte method**)
                        responseData = System.Text.Encoding.ASCII.GetString(data, 0, bytes); //(**This converts it to string**)

                        Form_Login.weightData = responseData;

                        lblWeight.Text = responseData;
                        //-------------------------------


                    }
                }
                catch (Exception)
                {


                }

            }
            //        '    If objSck.Client.Available > 0 Then
            //        '        Dim remoteEP As System.Net.IPEndPoint = Nothing
            //        '        Dim dat2 As Byte() = New [Byte](255) {}
            //        '        stream.Read(dat2, 0, dat2.Length)
            //        '        'Dim dat2 As Byte() = objSck.Receive(remoteEP)

            //        '        Dim result As String = System.Text.Encoding.ASCII.GetString(dat2, 0, dat2.Length)
            //        '        'MsgBox("result = [" & result & "]")

            //        '        Exit For
            //        '    End If


            //            if (objSck.Client.Available > 0)
            //{
            //     System.Net.IPEndPoint remoteEP = null;
            //                Byte[] dat2 = New [Byte](255); 
            //                stream.Read(dat2, 0, dat2.Length);
            //                String result = System.Text.Encoding.ASCII.GetString(dat2, 0, dat2.Length);



            //}


        }




        private void btnMainMenu_Click(object sender, EventArgs e)
        {
            IsProcess = false;

            //try
            //{
            //    IsProcess = false;
            //    Bluetooth.btBluetoothClose();
            //    Form_Menu._Form_MenuInstance.Show();                
            //    this.Close();
            //}
            //catch (Exception)
            //{
            //    Form_Menu._Form_MenuInstance.Show();
            //    this.Close();

            //}

            try
            {
                Bluetooth.btBluetoothClose();
                handler.Close();

                listener.Close();
                Form_Menu._Form_MenuInstance.Show();
                this.Close();
            }
            catch (Exception)
            {

            }



        }

        private void btnClear_Click(object sender, EventArgs e)
        {
            Clear();
        }

        private void Clear()
        {
            btnConnect.Enabled = true;
            client.Close();
            lblError.Text = string.Empty;
            lblWeight.Text = string.Empty;
            tbxWeight.Text = string.Empty;
            btnClear.Focus();

        }

        private void Print(string wight)
        {
            int ret = 0;

            UInt32 io = 0;

            io += LibDef.BT_BICOM_STATUS_1;

            string strBuf = "";
            int ssize = 0;
            IntPtr pBufSet;
            byte[] bBuf = new byte[] { };

            StringBuilder sb = new StringBuilder();
            sb.AppendLine();
            sb.AppendLine("<ESC>A");
            sb.AppendLine("<ESC>H0050<ESC>V0100<ESC>BQ3010,0");
            sb.AppendLine(wight);
            sb.AppendLine("<ESC>H0050<ESC>V0400<ESC>L0303<ESC>S");
            sb.AppendLine(wight);
            sb.AppendLine("<ESC>Z");
            String output = sb.ToString().Replace("<ESC>", "\x1B");

            strBuf = output;

            //MessageBox.Show(strBuf);

            if (strBuf.Length > 0)
            {

                bBuf = System.Text.Encoding.GetEncoding(GetCodePage()).GetBytes(strBuf);
                ssize = bBuf.Length;
                pBufSet = Marshal.AllocCoTaskMem(bBuf.Length);
                Marshal.Copy(bBuf, 0, pBufSet, ssize);

                //ret = BiCom.btBiComSend(pBufSet, Convert.ToUInt32(ssize), Convert.ToUInt32(io));
                ret = Bluetooth.btBluetoothSPPSend(pBufSet, Convert.ToUInt32(ssize), ref io);
                if (ret != LibDef.BT_OK)
                {
                    lblError.Text = "Print Error";
                    lblError.ForeColor = Color.Red;
                    //MessageBox.Show("Please print again");

                }
                else
                {
                    lblError.Text = "Print Correct";
                    lblError.ForeColor = Color.Green;
                }

                Marshal.FreeCoTaskMem(pBufSet);
            }
        }

        private int GetCodePage()
        {
            short lang = GetUserDefaultUILanguage();
            if ((lang == 0x804))
                return 936; // Simplified Chinese
            else if ((lang == 0x411))
                return 932;  // Japanese
            else if ((lang == 0x409))
                return 0; // English(US)
            else
                return 0;
        }

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

            //    case "F1":
            //        btnMainMenu_Click(sender, e);

            //        break;

            //    case "F2":
            //        btnConnect_Click_1(sender, e);

            //        break;

            //    case "F3":
            //        btnPrint_Click(sender, e);

            //        break;

            //    case "F4":

            //        btnClear_Click(sender, e);

            //        break;
            //}




        }

        private void btnPrint_Click(object sender, EventArgs e)
        {
            //Print(lblWeight.Text);
            //Print(tbxWeight.Text);
        }



        private void btnConnect_Click_1(object sender, EventArgs e)
        {
            try
            {
                //Byte[] sendByte = System.Text.Encoding.ASCII.GetBytes("WR EM" + "" + ".H " + "" + "\r");

                //stream.Write(sendByte, 0, sendByte.Length);

                timer1.Enabled = true;

                //btnConnect.Enabled = false;

                //bool Valid = connectPLC(remotePort, remoteHost);


            }
            catch (Exception)
            {

                MessageBox.Show("Connection Error");
            }
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            if (IsProcess == false)
            {
                timer1.Enabled = false;
                //client.Close();
                //listener.Close();

                try
                {
                    Bluetooth.btBluetoothClose();
                    Form_Menu._Form_MenuInstance.Show();
                    this.Close();
                }
                catch (Exception)
                {
                    Form_Menu._Form_MenuInstance.Show();
                    this.Close();

                }

                return;

            }

            if (IsClose == true)
            {
                //btnConnect.Enabled = false;

                IsClose = false;

                bool Valid = connectPLC(remotePort, remoteHost);

                timer1.Enabled = false;

                timer2.Enabled = true;

                //bool Valid = handlerReceive();                

                if (Valid == false)
                {
                    timer1.Enabled = false;
                    MessageBox.Show("Connection Error");
                    //btnConnect.Enabled = true;

                    Bluetooth.btBluetoothClose();
                    Form_Menu._Form_MenuInstance.Show();
                    this.Close();
                }
                else
                {
                    if (lblWeight.Text != string.Empty)
                    {
                        //Print(lblWeight.Text);
                    }
                    else
                    {
                        lblError.Text = string.Empty;
                    }
                }
            }


        }

        private void timer2_Tick(object sender, EventArgs e)
        {
            try
            {
                if (Form_Login.IsAppExit == true)
                {
                    //handler.Shutdown(SocketShutdown.Both);
                    //handler.Close();
                    listener.Shutdown(SocketShutdown.Both);
                    listener.Close();
                    this.Dispose();
                    this.Close();
                    return;
                }

                if (Form_Login.IsCloseShare == true)
                {
                    
                    //listener.Shutdown(SocketShutdown.Both);
                    //listener.Close();
                    //this.Dispose();
                    //this.Close();
                    this.Hide();
                }

                if (Form_Login.IsContinue == false)
                {
                    return;
                }
                               

            bool Valid = handlerReceive();

            if (Valid == false)
            {
                timer1.Enabled = false;
                MessageBox.Show("Connection Error");
                //btnConnect.Enabled = true;

                Bluetooth.btBluetoothClose();
                Form_Menu._Form_MenuInstance.Show();
                this.Close();
            }
            else
            {
                //MessageBox.Show(wightBefore);

                if ((lblWeight.Text != string.Empty) && !lblWeight.Text.Contains("0.00") && !lblWeight.Text.Contains("0.000") && (lblWeight.Text != wightBefore))
                {
                    //Print(lblWeight.Text);

                    wightBefore = lblWeight.Text;

                    Form_Login.weightData = lblWeight.Text.Substring(0, lblWeight.Text.Length - 3);

                    Form_Login.IsContinue = false;

                    //timer2.Enabled = false;
                    //DialogResult dialogResult = MessageBox.Show("Continue?", "Question", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button1);
                    //if (dialogResult == DialogResult.Yes)
                    //{
                    //    timer2.Enabled = true;
                    //}
                    //else if (dialogResult == DialogResult.No)
                    //{
                    //    Bluetooth.btBluetoothClose();                        
                    //    listener.Close();                        
                    //    Form_Menu._Form_MenuInstance.Show();                        
                    //    this.Close();
                    //}
                }
                else
                {
                    lblError.Text = string.Empty;
                    Form_Login.weightData = string.Empty;
                    Form_Login.IsContinue = true;
                }

                if (lblWeight.Text.Contains("0.00") && (lblWeight.Text.Contains("0.000")))
                {
                    wightBefore = lblWeight.Text;
                    Form_Login.IsContinue = false;
                }

            }
            }
            catch (Exception)
            {
                //this.Hide();
                Form_Login.IsContinue = false;
            }
        }

        private void Form_WeightDataToPrintB_Closing(object sender, CancelEventArgs e)
        {

        }
            

            //if ((lblWeight.Text != string.Empty) && (!lblWeight.Text.Contains("0.00") && (!lblWeight.Text.Contains("0.000"))))
            //{


                //timer2.Enabled = false;
                //DialogResult dialogResult = MessageBox.Show("Continue?", "Question", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button1);
                //if (dialogResult == DialogResult.Yes)
                //{
                //    timer2.Enabled = true;
                //}
                //else if (dialogResult == DialogResult.No)
                //{
                //    Bluetooth.btBluetoothClose();
                //    listener.Close();
                //    Form_Menu._Form_MenuInstance.Show();
                //    this.Close();
                //}

            //}

        //}




    }
}