using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

using nsAlienRFIDcf;



namespace nsAlienMobileSDK
{
    public partial class Form3 : Form
    {
        clsReader mReader;
        bool mbDisposing = false;
        static readonly string USERNAME = "alien";
        static readonly string PASSWORD = "password";
        static readonly string CONNECT_LOGIN = "Connect + Login";
        static readonly string DISCONNECT = "Disconnect";
        static readonly Color COLOR_WHITE = Color.White;
        static readonly Color COLOR_SYNCH = Color.Cyan;
        static readonly Color COLOR_DATA = Color.Magenta;
        static readonly Color COLOR_MSG = Color.Lime;
        static readonly Color COLOR_YELLOW = Color.Yellow;
        static readonly char CHAR_ZERO = Convert.ToChar((short)0);

        private delegate void showMsg();
        private delegate void showData();
        private delegate void showConnectionChanged();

        public Form3()
        {
            InitializeComponent();
        }

        private void Form_Load(object sender, EventArgs e)
        {
            AlienLog.Path = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + @"\AlienSDK\";
            mReader = new clsReader(true);
            mReader.Disconnected += new CBaseReader.DisconnectedEventHandler(mReader_Disconnected);
            mReader.Connected += new CBaseReader.ConnectedEventHandler(mReader_Connected);
            ManageGUI(false);
            listView1.Columns.Add(new ColumnHeader());
        }

        void mReader_Connected()
        {
            if (mbDisposing) return;
            showConnection(null);
            AlienLog.WriteLine(true, "in mReader_Connected()");
        }

        void mReader_Disconnected(string message)
        {
            if (mbDisposing) return;
            showConnection(message);
            AlienLog.WriteLine(true, "in mReader_Disconnected()");
        }

        void showConnection(string message)
        {
            lock (this)
            {
                showConnectionChanged method = delegate
                {
                    bool connected = (message == null) ? true : false;
                    if (message != null) 
                        addText(message.Replace("\0", ""), COLOR_YELLOW);
                    ManageGUI(connected);
                };
                this.BeginInvoke(method);
            }
        }

        void mReader_DataReceived(string data)
        {
            showReceived(data, COLOR_DATA);
            //AlienLog.WriteLine(true, "in mReader_DataReceived(): " + data);
        }

        void mReader_MessageReceived(string msg)
        {
            showReceived(msg, COLOR_MSG);
            AlienLog.WriteLine(true, "in mReader_MessageReceived(): " + msg);
        }

        void showReceived(string text, Color color)
        {
            if ((mbDisposing) || (text == null)) return;

            lock (this)
            {
                showMsg method = delegate
                {
                    addText(
                        text.Replace("\0", "[\\0]").Replace("\r\n", "[\\r\\n]" + CHAR_ZERO),
                        color);
                };
                this.BeginInvoke(method);
            }

        }


        private void Form_Closing(object sender, CancelEventArgs e)
        {
            mbDisposing = true;

            if (mReader != null)
                mReader.Dispose();

            mReader = null;
        }

        private void ManageGUI(bool connected)
        {
            txtIPAddress.Enabled = !connected;
            txtCommandPort.Enabled = !connected;
            txtTimeout.Enabled = !connected;
            label1.Enabled = !connected;
            label2.Enabled = !connected;
            label3.Enabled = !connected;
            chkKeepAlive.Enabled = !connected;

            rdoData.Enabled = connected;
            rdoMessage.Enabled = connected;
            rdoSendReceive.Enabled = connected;
            txtCommand.Enabled = connected;
            label4.Enabled = connected;
            lblSend1.Enabled = connected;
            btnExecute.Enabled = connected;

            btnConnect.Text = (connected ? DISCONNECT : CONNECT_LOGIN);
        }

        private void addText(string s, Color color)
        {
            //textBox1.Text += s.Replace("\0", "");
            //textBox1.Focus();
            //textBox1.SelectAll();
            //textBox1.ScrollToCaret();
            string[] lines = s.Split(CHAR_ZERO);
            for (int i = 0; i < lines.Length; i++)
            {
                ListViewItem item = new ListViewItem(lines[i]);
                item.ForeColor = color;
                listView1.Items.Add(item);
            }
            listView1.Refresh();
            Cursor.Current = Cursors.Default;
        }


        private void btnConnect_Click(object sender, EventArgs e)
        {
            Cursor.Current = Cursors.WaitCursor;
            bool isConnected = false;

            try
            {
                if (btnConnect.Text == CONNECT_LOGIN)
                {
                    mReader.ComTimeOutInterval = int.Parse(txtTimeout.Text) * 1000;

                    mReader.KeepNetworkConnectionAlive = chkKeepAlive.Checked;
                    //mReader.ConnectAndLogin(
                    //                        txtIPAddress.Text,
                    //                        int.Parse(txtCommandPort.Text),
                    //                        USERNAME,
                    //                        PASSWORD);
                    string ip = txtIPAddress.Text;
                    int port = (int)(int.Parse(txtCommandPort.Text));
                    mReader.InitOnNetwork(ip, port);
                    string result = mReader.Connect();
                    isConnected = mReader.IsConnected;
                    if (isConnected)
                    {
                        if (!mReader.Login(USERNAME, PASSWORD))
                            isConnected = false;
                    }
                }
                else
                {   
                    mReader.Disconnect(true, false);    // send "Q", raise Disconnected
                }
                isConnected = mReader.IsConnected;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
                Cursor.Current = Cursors.Default;
            }
            ManageGUI(isConnected);
        }


        private void btnClear_Click(object sender, EventArgs e)
        {
            txtCommand.Text = "";
            //textBox1.Text = "";
            listView1.Items.Clear();
            rdoData.Checked = false;
            rdoMessage.Checked = false;
            rdoSendReceive.Checked = false;
        }

        private void txtCommand_GotFocus(object sender, EventArgs e)
        {
            txtCommand.SelectAll();
        }

        private void rdoData_CheckedChanged(object sender, EventArgs e)
        {
            if (rdoData.Checked)
                mReader.DataReceived += new CBaseReader.DataReceivedEventHandler(mReader_DataReceived);
            else
                mReader.DataReceived -= new CBaseReader.DataReceivedEventHandler(mReader_DataReceived);
        }

        private void rdoMessage_CheckedChanged(object sender, EventArgs e)
        {
            if (rdoMessage.Checked)
                mReader.MessageReceived += new CBaseReader.MessageReceivedEventHandler(mReader_MessageReceived);
            else
                mReader.MessageReceived -= new CBaseReader.MessageReceivedEventHandler(mReader_MessageReceived);
        }

        private void btnExecute_Click(object sender, EventArgs e)
        {
            String command = txtCommand.Text.Trim();
            if (command.Length > 0)
            {
                try
                {
                    if (rdoSendReceive.Checked)
                        addText(    // blocking call
                            mReader.SendReceive(command, false).Replace("\0", "[\\0]").Replace("\r\n", "[\\r\\n]" + CHAR_ZERO), 
                            COLOR_SYNCH);  
                    else 
                        mReader.Send(command + "\r\n", false);   // asynchronous call
                }
                catch (Exception ex)
                {
                    addText("\r\n" + ex.Message, COLOR_WHITE);
                }
            }
        }


    }
}