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.Threading;
using OpenNETCF.Net.NetworkInformation;
using System.IO.Ports;
using System.Collections;
using System.Diagnostics;
using Microsoft.WindowsCE.Forms;


namespace WLANBasic1009
{
    public partial class Form1 : Form
    {
        
        private WLAN wifi;
        private String apSSID;
        private GPS myGps;
        public delegate void labelDelegate(String text);
        public delegate int listboxGps(Object text);
        public delegate void formRefreshDelegate();
        public delegate ListViewItem listViewAddDelegate(ListViewItem listViewItem);
        public delegate void listViewRefreshDelegate(AccessPointCollection apc);
        //graphDelegate myGraphDelegate;

        AccessPointCollection AccessPointsList;

        //private MyTimer myTimer;
        private Graph myGraph;
        private Settings mySettings;
        AccessPoint AP;
        //public delegate void graphDelegate(List<int> list);
        int timer = 0;
        private MyTimer myTimer;

        public static EventHandler mainFormEventHandler;
        //public static EventHandler graphEventHandler;
        //public static EventHandler settingsEventHandler;
        

        List<string> selectedMACs = new List<string>();

        public static bool refreshMainFrom = true;

        public Form1()
        {

            InitializeComponent();
            SystemSettings.ScreenOrientation = ScreenOrientation.Angle90;
            
            wifi = new WLAN();

            wifi.findNetworkNics();
                  
            #region ListView

            listView1.View = View.Details;
            //listView1.Columns.Add("G", 15, HorizontalAlignment.Center);
            listView1.Columns.Add("SSID", 80, HorizontalAlignment.Center);
            listView1.Columns.Add("RSS [dBm]", 80, HorizontalAlignment.Center);
            listView1.Columns.Add("Channel", 60, HorizontalAlignment.Center);
            listView1.Columns.Add("MAC", 120, HorizontalAlignment.Center);
            listView1.Columns.Add("Privacy", 80, HorizontalAlignment.Center);
            #endregion

            mainFormEventHandler = new EventHandler(mainFormTimerHandler);
           
            if (wifi.WZCCompatible())
            {
                AccessPointsList = wifi.WZCInterface.NearbyAccessPoints;
            }

            else
            {
                MessageBox.Show("No WiFi Adapter Found");
                Application.Exit();
            }
            MyTimer.isTime += new EventHandler(mainFormTimerHandler);
        }

        public void refresListView(AccessPointCollection accessPintList)
        {

            listViewAddDelegate addItem = delegate(ListViewItem listViewItem)
            {
                listView1.Items.Add(listViewItem);
                return listViewItem;
            };
            formRefreshDelegate clearListViewItems = delegate()
            {
                listView1.Items.Clear();
            };
            formRefreshDelegate formRefresh = delegate()
            {
                this.Focus();
            };

            formRefreshDelegate listViewRefresh = delegate()
            {
                listView1.Refresh();
            };

            List<AccessPoint> accessPointListSorted = accessPintList.ToList<AccessPoint>();
            accessPointListSorted.Sort((delegate(AccessPoint ap2, AccessPoint ap1)
            { return ap1.SignalStrength.Decibels.CompareTo(ap2.SignalStrength.Decibels); })
            ); 

            listView1.Invoke(clearListViewItems, new object[] { });
            
            foreach (AccessPoint ap in accessPointListSorted)
            {
                ListViewItem listViewItem = new ListViewItem(ap.Name.ToString());
                if (selectedMACs.Contains(ap.PhysicalAddress.ToString()))
                {
                    #region Display colored line in listView
                    int index = selectedMACs.IndexOf(ap.PhysicalAddress.ToString());
                    switch (index)
                    {
                        case 0:
                            listViewItem.BackColor = Color.Blue;
                            break;
                        case 1:
                            listViewItem.BackColor = Color.Green;
                            break;
                        case 2:
                            listViewItem.BackColor = Color.Red;
                            break;
                        case 3:
                            listViewItem.BackColor = Color.Violet;
                            break;
                        default:
                            listViewItem.BackColor = Color.White;
                            break;
                    }
                    #endregion
                }
                listViewItem.SubItems.Add(ap.SignalStrength.Decibels.ToString());
                listViewItem.SubItems.Add(ap.Channel.ToString());
                listViewItem.SubItems.Add(ap.PhysicalAddress.ToString());
                listViewItem.SubItems.Add(ap.Privacy == 0 ? "Open" : "WEP");
                listView1.Invoke(addItem, new object[] { listViewItem });
            }

            this.Invoke(listViewRefresh, new object[] { });
            this.Invoke(formRefresh, new object[] { });
        }
        /*public void handlerTimer(object sender, EventArgs args)
        {
            timer++;
            labelDelegate timerLabel = delegate(String text)
            {
                //label2.Text = text;
            };

            //label2.Invoke(timerLabel, new object[] { timer.ToString() });
            AccessPointsList.Refresh();
            if (myGraph == null && mySettings==null)
            {
                refresListView(AccessPointsList);
            }
            else if (myGraph != null)
            {
                myGraph.Invoke(myGraphDelegate, new object[] { selectedRSSI });
            }
            else if (mySettings != null)
            {
                //myGraph.Invoke(myGraphDelegate, new object[] { selectedRSSI });
            }
        }*/

        public void mainFormTimerHandler(object sender, EventArgs args)
        {
            if (refreshMainFrom)
            {
            AccessPointsList.Refresh();
            refresListView(AccessPointsList);
            LogSaver.saveToLog(AccessPointsList,selectedMACs);
            }
        }
        /*public void graphTimerHandler(object sender, EventArgs args)
        {
            AccessPointsList.Refresh();
            myGraph.Invoke(myGraphDelegate, new object[] { selectedRSSI });
        }*/
        /*public void settingsTimerHandler(object sender, EventArgs args)
        {
            AccessPointsList.Refresh();
        }*/

        public void comPortGPSHandler(object sender, EventArgs args)
        {
            if (refreshMainFrom)
            {
            labelDelegate gpsLatitudedelegate = delegate(String text)
            {
                label3.Text = text;
            };
            labelDelegate gpsLongitudedelegate = delegate(String text)
            {
                label4.Text = text;
            };

            List<String> gpsData  = GPS.getNewLine();

            label3.Invoke(gpsLatitudedelegate, new object[] {gpsData.ElementAt(0).ToString()});
            label3.Invoke(gpsLongitudedelegate, new object[] {gpsData.ElementAt(1).ToString()});
            }

        }

        private void menuItem1_Click(object sender, EventArgs e)
        {
            if (LogSaver.tw != null)
            {
                LogSaver.closeLogFile();
            }
            Application.Exit();
            if(myTimer!=null)myTimer.stopTimer();
            if (GPS.com8.IsOpen)
            {
                GPS.closeGPSport();
            }
            SystemSettings.ScreenOrientation = ScreenOrientation.Angle0;
        }

        private void label1_ParentChanged(object sender, EventArgs e)
        {
        }

        private void button1_Click(object sender, EventArgs e)
        {
            refreshMainFrom = false;
            myGraph = new Graph(AccessPointsList,selectedMACs);
            MyTimer.isTime -= mainFormEventHandler;
            MyTimer.isTime += Graph.graphEventHandler;
            myGraph.Activate();
            myGraph.Show();
        }

        private void button2_Click(object sender, EventArgs e)
        {
            //myTimer = new MyTimer();
        }

        private void label3_ParentChanged(object sender, EventArgs e)
        {

        }

        private void button2_Click_1(object sender, EventArgs e)
        {
            //myGps = new GPS();
            if (button2.Text == "StartGPS")
            {
                //MessageBox.Show("StartGPS");
                GPS.newLineAvailable += new EventHandler(comPortGPSHandler);
                GPS.openGPSCOMPort();
                button2.Text = "StopGPS";
            }
            else
            {
                GPS.closeGPSport();
                button2.Text = "StartGPS";
            }
        }

        private void button3_Click(object sender, EventArgs e)
        {
            wifi.findNetworkNics();
            //label1.Text = "Network Interfaces";

            if (wifi.WZCCompatible())
            {
                try
                {
                    //listBox1.Items.Clear();
                }
                catch (Exception ex) { }

                foreach (AccessPoint AP in wifi.WZCInterface.NearbyAccessPoints)
                {
                    try
                    {
                        //listBox1.Items.Add(AP.Name);
                    }
                    catch (Exception ex) { }
                }
            }
        }



        private void button1_GotFocus(object sender, EventArgs e)
        {

        }

        private void Form1_GotFocus(object sender, EventArgs e)
        {
            button3_Click(this, new EventArgs());
        }

        private void Form1_Activated(object sender, EventArgs e)
        {
            button3_Click(this, new EventArgs());
        }

        private void Form1_Load(object sender, EventArgs e)
        {

        }

        private void Form1_Closing(object sender, CancelEventArgs e)
        {
            
        }

        private void Form1_Closed(object sender, EventArgs e)
        {
            SystemSettings.ScreenOrientation = ScreenOrientation.Angle0;
        }

        private void dataGrid1_CurrentCellChanged(object sender, EventArgs e)
        {

        }

        private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
        {

        }

        private void dataGrid1_CurrentCellChanged_1(object sender, EventArgs e)
        {

        }

        private void listView1_SelectedIndexChanged(object sender, EventArgs e)
        {
            string selectedMac;
            if (listView1.SelectedIndices.Count != 0)
            {
                selectedMac = listView1.Items[listView1.SelectedIndices[0]].SubItems[3].Text.ToString();
                if (selectedMACs.Contains(selectedMac))
                {
                    buttonSelect.Text = "Unselect";
                }
                else
                {
                    buttonSelect.Text = "Select";
                }
            }
                
        }

        private void Form1_KeyDown(object sender, KeyEventArgs e)
        {
            if ((e.KeyCode == System.Windows.Forms.Keys.Up))
            {
                // Up
            }
            if ((e.KeyCode == System.Windows.Forms.Keys.Down))
            {
                // Down
            }
            if ((e.KeyCode == System.Windows.Forms.Keys.Left))
            {
                // Left
            }
            if ((e.KeyCode == System.Windows.Forms.Keys.Right))
            {
                // Right
            }
            if ((e.KeyCode == System.Windows.Forms.Keys.Enter))
            {
                // Enter
            }

        }

        private void label2_ParentChanged(object sender, EventArgs e)
        {

        }

        private void label4_ParentChanged(object sender, EventArgs e)
        {

        }

        private void button3_Click_1(object sender, EventArgs e)
        {
            if (((Button)sender).Text == "Stop")
            {
                buttonScan.Text = "Scan";
                myTimer.stopTimer();
            }
            else
            {
                buttonScan.Text = "Stop";
                myTimer = new MyTimer();
            }
        }

        private void button4_Click(object sender, EventArgs e)
        {

        }

        private void button5_Click(object sender, EventArgs e)
        {
            if ((listView1.SelectedIndices).Count != 0)
            {
                string selectedMac;
                //MessageBox.Show(  listView1.SelectedIndices[0].ToString());
                selectedMac = listView1.Items[listView1.SelectedIndices[0]].SubItems[3].Text.ToString();
                //listView1.Items[listView1.SelectedIndices[0]].BackColor = Color.Red;
                //MessageBox.Show(listView1.Items[listView1.SelectedIndices[0]].SubItems[3].Text.ToString());
                if (!selectedMACs.Contains(selectedMac))
                {
                    if (selectedMACs.Count < 3)
                    {
                        selectedMACs.Add(selectedMac);
                        buttonSelect.Text = "Unselect";
                    }
                }
                else 
                {
                    selectedMACs.Remove(selectedMac);
                    buttonSelect.Text = "Select";
                }
                
            }
            
        }

        private void label1_ParentChanged_1(object sender, EventArgs e)
        {

        }

        private void menuItem2_Click(object sender, EventArgs e)
        {
            refreshMainFrom = false;
            MyTimer.isTime -= mainFormEventHandler;
            mySettings = new Settings();
            MyTimer.isTime += Settings.settingsEventHandler;
            mySettings.Activate();
            mySettings.Show();
        }

        private void Form1_Deactivate(object sender, EventArgs e)
        {
            //menuItem1_Click(sender, e);
        }
    }
}

