/*
 *
 * Copyright (C) 2015 Texas Instruments Incorporated - http://www.ti.com/
 *
 *
 *  Redistribution and use in source and binary forms, with or without
 *  modification, are permitted provided that the following conditions
 *  are met:
 *
 *    Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 *
 *    Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the
 *    distribution.
 *
 *    Neither the name of Texas Instruments Incorporated nor the names of
 *    its contributors may be used to endorse or promote products derived
 *    from this software without specific prior written permission.
 *
 *  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 *  "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 *  LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 *  A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 *  OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 *  SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 *  LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 *  DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 *  THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 *  (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 *  OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 */
using System;
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.IO;
using System.Threading;

namespace RadioToolGUI
{
    internal partial class frmMain : Form
    {
        #region Members
        /*===================================================================*/
        private ConnectTab m_ConnectTab;
        private TxTab m_TxTab;
        private RxTab m_RxTab;

        internal static BackgroundWorker RadioToolThread = null;
        /*===================================================================*/
        #endregion /* Members */

        #region Access
        /*===================================================================*/
        /*===================================================================*/
        #endregion /* Access */

        #region LifeCycle
        /*===================================================================*/
        /// <summary>
        /// Mandatory Constructor for initializing the Form.
        /// </summary>
        /// <param name="gui_manager"></param>
        /// <returns></returns>
        internal frmMain()
        {
            //This fixes system font inconsistancy issue
            Font = new Font(SystemFonts.MessageBoxFont.FontFamily, 8.25F, SystemFonts.MessageBoxFont.Style);

            InitializeComponent();
            //Additional operation to add version number:
            this.Text = Properties.Resources.default_app_title + GlobalReference.GetAssemblyVersion();

            //this.HideOnClose = true;
            GlobalReference.ConsoleInitialization(this, rtxtConsole);

            iInitTabs();

            //Check DLL files
            DLLInfo DLLinfo = GlobalReference.CheckDLLFile();
            m_lbl3120LibVer.Text = DLLinfo.Lib3120Version.ToString();
            m_lbl3120LibUARTVer.Text = DLLinfo.Lib3120UARTVersion.ToString();
            m_lbl3220LibVer.Text = DLLinfo.Lib3220Version.ToString();

            Boolean all_lib_present = true;
            StringBuilder lib_error_msg = new StringBuilder();
            lib_error_msg.Append("Missing the following library file(s). Please check your installation.");

            if (!DLLinfo.Lib3120SPIExist)
            {
                lib_error_msg.Append("\nCC3120Lib.dll");
                all_lib_present = false;
            }

            if (!DLLinfo.Lib3120UARTExist)
            {
                lib_error_msg.Append("\nCC3120LibUART.dll");
                all_lib_present = false;
            }

            if (!DLLinfo.Lib3220Exist)
            {
                lib_error_msg.Append("\nCC3220Lib.dll");
                all_lib_present = false;
            }

            if (!all_lib_present)
            {
                MessageBox.Show(lib_error_msg.ToString(), "Missing Library Files.", MessageBoxButtons.OK, MessageBoxIcon.Error, MessageBoxDefaultButton.Button1);
            }

            GlobalReference.WriteConsole("Program Ready, version " + GlobalReference.GetAssemblyVersion());
        }
        /*===================================================================*/
        #endregion /* LifeCycle */

        #region Operations
        /*===================================================================*/
        /// <summary>
        /// Initializing all tabs.
        /// </summary>
        private void iInitTabs()
        {
            m_ConnectTab = new ConnectTab(this);
            m_TxTab = new TxTab(this);
            m_RxTab = new RxTab(this);

            m_tabConnectionHolder.Controls.Add(m_ConnectTab);
            m_tabTxHolder.Controls.Add(m_TxTab);
            m_tabRxHolder.Controls.Add(m_RxTab);
        }

        protected override void OnFormClosing(FormClosingEventArgs e)
        {
            base.OnFormClosing(e);
            if (GlobalReference.isDeviceConnected())
                GlobalReference.DisconnectDevice();
        }

        internal void UpdateDeviceInfo()
        {
            m_lblChipId.Text = GlobalReference.MyCurrentDevice.ChipId;
            m_lblRomVer.Text = GlobalReference.MyCurrentDevice.RomVer;
            m_txtFwVer.Text = GlobalReference.MyCurrentDevice.FwVer;
            m_txtNwpVer.Text = GlobalReference.MyCurrentDevice.NwpVer;
            m_txtPhyVer.Text = GlobalReference.MyCurrentDevice.PhyVer;
            m_txtHostDriverVer.Text = GlobalReference.MyCurrentDevice.HostDriverVer;
            m_txtMacAddress.Text = GlobalReference.MyCurrentDevice.mac;
            m_txtCC3220AppVer.Text = GlobalReference.MyCurrentDevice.CC3220AppVer;
        }

        /// <summary>
        /// Change connection status text.
        /// </summary>
        internal void updateConnectionStatus(String status)
        {
            m_txtConnection.Text = status;

            switch (status)
            {
                case GlobalReference.CONNECTION_STATUS_CONNECTED:
                    m_txtConnection.BackColor = Color.Lime;
                    break;
                case GlobalReference.CONNECTION_STATUS_CONNECTING:
                    m_TxTab.EnableControls(false);
                    m_RxTab.EnableControls(false);
                    m_txtConnection.BackColor = Color.Green;
                    break;
                case GlobalReference.CONNECTION_STATUS_DISCONNECTED:
                    m_TxTab.EnableControls(false);
                    m_RxTab.EnableControls(false);
                    m_txtConnection.BackColor = Color.OrangeRed;
                    break;
                case GlobalReference.CONNECTION_STATUS_DISCONNECTING:
                    m_TxTab.EnableControls(false);
                    m_RxTab.EnableControls(false);
                    m_txtConnection.BackColor = Color.LightCoral;
                    break;
                case GlobalReference.CONNECTION_STATUS_NA:
                    m_txtConnection.BackColor = System.Drawing.SystemColors.Control;
                    break;
                default:
                    break;
            }
        }

        /// <summary>
        /// Change testing status text and related fields.
        /// </summary>
        internal void updateTestingStatus(String status)
        {
            m_txtTestingStatus.Text = status;

            switch(status){
                case GlobalReference.TESTING_STATUS_NA:
                    m_txtTestingStatus.BackColor = System.Drawing.SystemColors.Control;
                    break;
                case GlobalReference.TESTING_STATUS_IDLE:
                    m_TxTab.EnableControls(true);
                    m_RxTab.EnableControls(true);
                    m_ConnectTab.EnableControls(true);
                    m_txtTestingStatus.BackColor = System.Drawing.SystemColors.Control;
                    break;
                case GlobalReference.TESTING_STATUS_FETCHING_INFO:
                    m_txtTestingStatus.BackColor = Color.NavajoWhite;
                    break;
                case GlobalReference.TESTING_STATUS_TX_RUNNING:
                    m_RxTab.EnableControls(false);
                    m_ConnectTab.EnableControls(false);
                    m_txtTestingStatus.BackColor = Color.Cyan;
                    break;
                case GlobalReference.TESTING_STATUS_TX_STOPPING:
                    m_txtTestingStatus.BackColor = Color.Cyan;
                    break;
                case GlobalReference.TESTING_STATUS_RX_RUNNING:
                    m_TxTab.EnableControls(false);
                    m_ConnectTab.EnableControls(false);
                    m_txtTestingStatus.BackColor = Color.Violet;
                    break;
                case GlobalReference.TESTING_STATUS_RX_STOPPING:
                    m_txtTestingStatus.BackColor = Color.Violet;
                    break;
                default:
                    m_txtTestingStatus.BackColor = System.Drawing.SystemColors.Control;
                    break;
            }
        }

        /// <summary>
        /// Change target device text.
        /// </summary>
        /// <param name="target_device">One of the GlobalReferece's TARGET_DEVICE_*</param>
        internal void updateTargetDevice(String target_device)
        {
            m_txtTargetDevice.Text = target_device;
        }
        /*===================================================================*/
        #endregion /* Operations */

        #region Event Handling
        /*===================================================================*/
        /// <summary>
        /// Clear console text.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void m_btnClear_Click(object sender, EventArgs e)
        {
            rtxtConsole.Clear();
        }

        /// <summary>
        /// Copy console text to clipboard
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void m_btnCopyToClipboard_Click(object sender, EventArgs e)
        {
            if (!String.IsNullOrEmpty(rtxtConsole.Text))
            {
                Clipboard.SetText(rtxtConsole.Text);
            }
        }

        /// <summary>
        /// Save console text to file.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void m_btnExportLog_Click(object sender, EventArgs e)
        {
            SaveFileDialog saveFileDialog1 = new SaveFileDialog();

            saveFileDialog1.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*";
            saveFileDialog1.FilterIndex = 1;
            saveFileDialog1.RestoreDirectory = true;

            if (saveFileDialog1.ShowDialog() == DialogResult.OK)
            {
                Stream myStream = saveFileDialog1.OpenFile();
                if (myStream != null)
                {
                    // Code to write the stream goes here.
                    StreamWriter sw = new StreamWriter(myStream);
                    sw.Write(rtxtConsole.Text);
                    sw.Flush();
                    sw.Close();
                    myStream.Close();
                }
            }
        }

        private void m_btnAbout_Click(object sender, EventArgs e)
        {
            AboutBox aboutWindow = new AboutBox();
            aboutWindow.Show();
        }

        private void m_btnWikiLink_Click(object sender, EventArgs e)
        {
            String url = "http://processors.wiki.ti.com/index.php/CC31xx_%26_CC32xx_Radio_Tool";
            System.Diagnostics.Process.Start(url);
        }

        private void label7_Click(object sender, EventArgs e)
        {

        }
        /*===================================================================*/
        #endregion /* Event Handling */

        private void label1_Click(object sender, EventArgs e)
        {

        }
    }
}
