using System;
using System.Linq;
using System.Collections.Generic;
using System.Text;
using System.Windows.Forms;
using System.IO.Ports;
using Bt;
using Bt.CommLib;
using Bt.SysLib;

namespace HT_SKT_Stock
{
    class BtCommLib
    {
        static LogWriter logger = LogWriter.getInstance(); 

        public static void openUsb()
        {
            Int32 ret = 0;
            String disp = "";
            String strEnable = "";

            Int32 enableDef = 0;
            UInt32 funcTypeDef = 0;
            UInt32 storageTypeDef = 0;
            UInt32 funcTypeSet = 0;
            UInt32 storageTypeSet = 0;
            Int32 enableGet = 0;
            UInt32 funcTypeGet = 0;
            UInt32 storageTypeGet = 0;

            try
            {
                //-----------------------------------------------------------
                // Acquire before setting
                //-----------------------------------------------------------
                ret = Usb.btUSBGetSetting(ref enableDef, ref funcTypeDef, ref storageTypeDef);
                if (ret != LibDef.BT_OK)
                {
                    disp = "btUSBGetSetting error ret[" + ret + "]";
                    MessageBox.Show(disp, "Error");
                    return;
                }
                if (enableDef == 1)
                {
                    strEnable = "Enable";
                }
                else if (enableDef == 0)
                {
                    strEnable = "Disable";
                }
                disp =
                    "Enable/Disable:" + strEnable + "\r\n" +
                    "Function:" + funcTypeDef + "\r\n" +
                    "Public storage:" + storageTypeDef + "\r\n";
                //MessageBox.Show(disp, "Communication unit settings (before being set)");

                //-----------------------------------------------------------
                // Settings
                //-----------------------------------------------------------
                ret = Usb.btUSBClose();
                if (ret != LibDef.BT_OK)
                {
                    disp = "btUSBClose error ret[" + ret + "]";
                    MessageBox.Show(disp, "Error");
                    goto L_END;
                }

                funcTypeSet = LibDef.BT_USB_CLIENT_COM;
                storageTypeSet = LibDef.BT_USB_STORAGE_SD;
                ret = Usb.btUSBOpen(funcTypeSet, storageTypeSet);
                if (ret != LibDef.BT_OK)
                {
                    disp = "btUSBOpen error ret[" + ret + "]";
                    MessageBox.Show(disp, "Error");
                    goto L_END;
                }

                ret = Usb.btUSBGetSetting(ref enableGet, ref funcTypeGet, ref storageTypeGet);
                if (ret != LibDef.BT_OK)
                {
                    disp = "btUSBGetSetting error ret[" + ret + "]";
                    MessageBox.Show(disp, "Error");
                    goto L_END;
                }
                if (enableGet == 1)
                {
                    strEnable = "Enable";
                }
                else if (enableGet == 0)
                {
                    strEnable = "Disable";
                }
                disp =
                    "Enable/Disable:" + strEnable + "\r\n" +
                    "Function:" + funcTypeGet + "\r\n" +
                    "Public storage:" + storageTypeGet + "\r\n";
                //MessageBox.Show(disp, "Communication unit settings (after being set)");

            L_END:
                //-----------------------------------------------------------
                // Return to save
                //-----------------------------------------------------------
                ret = Usb.btUSBClose();
                if (ret != LibDef.BT_OK)
                {
                    disp = "btUSBClose error ret[" + ret + "]";
                    MessageBox.Show(disp, "Error");
                }

                funcTypeSet = funcTypeDef;
                storageTypeSet = storageTypeDef;
                ret = Usb.btUSBOpen(funcTypeSet, storageTypeSet);
                if (ret != LibDef.BT_OK)
                {
                    disp = "btUSBOpen error ret[" + ret + "]";
                    MessageBox.Show(disp, "Error");
                }
            }
            catch (Exception ex)
            {
             
            }
        }

        /********************************************************************************
         * Function: Acquire whether USB communication can/cannot be performed. 
         * API: btUSBGetConnectStatus
        ********************************************************************************/
        public static Int32 checkUsbStatus()
        {
            Int32 ret = 0;
            String disp = "";
            String strEnable = "";

            Int32 enableGet = 0;

            try
            {
                ret = Usb.btUSBGetConnectStatus(ref enableGet);
                if (ret != LibDef.BT_OK)
                {
                    disp = "btUSBGetConnectStatus error ret[" + ret + "]";
                    //MessageBox.Show(disp, "Error");
                    return 0;
                }
                if (enableGet == 1)
                {
                    strEnable = "Communication is possible.";
                }
                else if (enableGet == 0)
                {
                    strEnable = "Communication is not possible.";
                }
                disp = strEnable + "\r\n";
                //MessageBox.Show(disp, "Acquire communication unit connection status");
            }
            catch (Exception ex)
            {
             
            }

            return enableGet;
        }

        public static int listen(string logFile)
        {
            int ret = 0;
            try
            {
                // log => AppPath + "\\KPListen.txt"
                ret = KProtocol.btCommListen(10, LibDef.BT_VK_CLR, new StringBuilder(logFile));
                if (ret != LibDef.BT_OK)
                {
                    //MessageBox.Show("btCommListen error ret[" + ret + "]", "Error", MessageBoxButtons.OK, MessageBoxIcon.Exclamation, MessageBoxDefaultButton.Button1);
                }
            }
            catch (Exception ex)
            {
                //MessageBox.Show(ex.ToString());
            }

            return ret;
        }

        public static int connect(uint timeout)
        {
            int ret = 0;

            try
            {
                // Client create connection
                ret = KProtocol.btCommConnect(timeout, LibDef.BT_VK_CLR);
                if (ret != LibDef.BT_OK)
                {
                    logger.Log("btCommConnect error ret[" + ret + "]");
                    return ret;
                }
            }
            catch (Exception ex)
            {
                logger.Log(ex.ToString());
            }

            return ret;
        }

        public static int disconnect(uint timeout)
        {
            int ret = 0;

            try
            {
                // Client disconnect
                ret = KProtocol.btCommDisconnect(timeout, LibDef.BT_VK_CLR);
                if (ret != LibDef.BT_OK)
                {
                    logger.Log("btCommDisconnect error ret[" + ret + "]");
                    return ret;
                }
            }
            catch (Exception ex)
            {
                logger.Log(ex.ToString());
            }

            return ret;
        }

        public static bool downloadFile(string local, string remote)
        {
            bool result = false;
            StringBuilder localFile = new StringBuilder(local);
            StringBuilder remoteFile = new StringBuilder(remote);

            try
            {
                logger.Log(String.Format("download file: local=>{0},remote=>{1}",
                    local, remote));
                Int32 ret = KProtocol.btCommGetFile(remoteFile, localFile, 10, LibDef.BT_VK_CLR);
                if (ret != LibDef.BT_OK)
                {
                    logger.Log("btCommGetFile error ret[" + ret + "]");
                    return false;
                }
                MessageBox.Show("file downloaded");
                result = true;
            }
            catch (Exception ex)
            {
                logger.Log(ex.ToString());
            }

            return result;
        }

        public static bool uploadFile(string local, string remote, bool overWrite, bool createFolder)
        {
            bool result = false;
            StringBuilder localFile = new StringBuilder(local);
            StringBuilder remoteFile = new StringBuilder(remote);

            try
            {
                logger.Log(String.Format("upload file: local=>{0},remote=>{1},overWrite=>{2},createFolder=>{3}",
                    local, remote, overWrite, createFolder));
                Int32 ret = KProtocol.btCommPutFile(localFile, remoteFile, overWrite, createFolder, 10, LibDef.BT_VK_CLR);
                if (ret != LibDef.BT_OK)
                {
                    logger.Log("btCommPutFile error ret[" + ret + "]");
                    return result;
                }
                logger.Log("file uploaded");
                result = true;
            }
            catch (Exception ex)
            {
                logger.Log(ex.ToString());
            }

            return result;
        }

        public static void COMSend()
        {
            String disp = "";

            SerialPort serialPort1 = new SerialPort();

            try
            {
                // Serial port name settings
                serialPort1.PortName = "COM1";
                // Specify serial port communication speed
                serialPort1.BaudRate = 9600;
                // Specify serial port parity
                serialPort1.Parity = System.IO.Ports.Parity.None;
                // Specify number of serial port bits
                serialPort1.DataBits = 8;
                // Specify serial port stop bit 
                serialPort1.StopBits = System.IO.Ports.StopBits.One;
                // Open serial port
                serialPort1.Open();
                // Transmit data to serial port
                String sendMsg = "Hello!!";
                Byte[] dat =
                    System.Text.Encoding.GetEncoding(932).GetBytes(sendMsg);
                serialPort1.Write(dat, 0, dat.GetLength(0));

                disp = "Data to transmit:" + sendMsg + "\r\nInput data with serial port communication terminal and then press OK.";
                MessageBox.Show(disp, "Virtual COM communication");

                // Receive data from serial port
                Byte[] dat2 = new Byte[serialPort1.BytesToRead];
                serialPort1.Read(dat2, 0, dat2.GetLength(0));
                disp = "Received data:" + System.Text.Encoding.GetEncoding(932).GetString(dat2, 0, dat2.Length);
                MessageBox.Show(disp, "Virtual COM communication");

                // Close serial port
                serialPort1.Close();
            }
            catch (Exception ex)
            {
              
            }
        }
    }
}
