/*******************************************************************************
* Copyright (C) 2016 Maxim Integrated Products, Inc., All rights Reserved.
* 
* This software is protected by copyright laws of the United States and
* of foreign countries. This material may also be protected by patent laws
* and technology transfer regulations of the United States and of foreign
* countries. This software is furnished under a license agreement and/or a
* nondisclosure agreement and may only be used or reproduced in accordance
* with the terms of those agreements. Dissemination of this information to
* any party or parties not specified in the license agreement and/or
* nondisclosure agreement is expressly prohibited.
*
* The above copyright notice and this permission notice shall be included
* in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
* OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
* IN NO EVENT SHALL MAXIM INTEGRATED BE LIABLE FOR ANY CLAIM, DAMAGES
* OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
* ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
*
* Except as contained in this notice, the name of Maxim Integrated
* Products, Inc. shall not be used except as stated in the Maxim Integrated
* Products, Inc. Branding Policy.
*
* The mere transfer of this software does not imply any licenses
* of trade secrets, proprietary technology, copyrights, patents,
* trademarks, maskwork rights, or any other form of intellectual
* property whatsoever. Maxim Integrated Products, Inc. retains all
* ownership rights.
*******************************************************************************
*/

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

using System.IO.Ports;

namespace HealthSensorPlatform
{
    public partial class FormConnection : Form
    {
        string port;
        bool done = false;
        //bool canceled = false;
        //bool connect = false;

        public bool Canceled { get; set; }
       // public bool Connect { get; set; }

        internal const Int32 WM_DEVICECHANGE = 0x219;
        internal const Int32 DBT_DEVICEARRIVAL = 0x8000;
        internal const Int32 DBT_DEVICEREMOVECOMPLETE = 0x8004;

        public FormConnection()
        {
            InitializeComponent();
            ScanPorts();

            port = Properties.Settings.Default.ComPort;
        }

        private void btnConnect_Click(object sender, EventArgs e)
        {
            if (cboPort.SelectedItem != null)
            {
                port = cboPort.SelectedItem.ToString();

                // Save default COM port for next application use
                Properties.Settings.Default["ComPort"] = Port;
                Properties.Settings.Default.Save();

                done = true;
                Close();
            }
            else
            {
                MessageBox.Show("Selected port is invalid.", "Connection");
            }
        }

        /// <summary>
        /// Reset the state of the connection Form.
        /// </summary>
        public void Reset()
        {
            Canceled = false;
        }


        /// <summary>
        /// Returns default port saved in Properties.Settings.Default.ComPort
        /// if port is not selected or user selected port from drop down menu
        /// </summary>
        /// <returns></returns>
        public string Port
        {
            get { return port; }
        }
       

        private void btnScan_Click(object sender, EventArgs e)
        {
            ScanPorts();

        }

        /// <summary>
        /// Scan the port names
        /// </summary>
        public void ScanPorts()
        {
            string[] ports = SerialPort.GetPortNames();

            cboPort.Items.Clear();
            //cboPort.SelectedItem = null;
            cboPort.SelectedIndex = -1;

            foreach (string port in ports)
            {
                cboPort.Items.Add(port);

                if(String.Compare(port,Properties.Settings.Default.ComPort) == 0)
                {
                    // Select the last used COM Port
                    cboPort.SelectedItem = Properties.Settings.Default.ComPort;
                }
            }
            
        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            Canceled = true;
            done = true;
            Close();
        }

        public bool HandleWMDeviceChangeMessage(Message m)
        {
            string[] ports;
            bool removal = false;

            if (m.Msg == WM_DEVICECHANGE)
            {
                if (m.WParam.ToInt32() == DBT_DEVICEREMOVECOMPLETE)
                {
                    ports = SerialPort.GetPortNames();

                    foreach(string p in ports)
                    {
                        if (String.Compare(p, Port) == 0)
                        {
                            removal = true;
                            break;
                        }
                    }
                }

            }

            return removal;
        }

        private void FormConnection_FormClosing(object sender, FormClosingEventArgs e)
        {
            // User clicked "X" button to close form,
            // action should be the same as if user clicked on "Canceled" button
            if (done == false)
                Canceled = true;
        }
    }
}
