using System;
using System.Linq;
using System.Collections.Generic;
using System.Text;
using System.IO.Ports;

namespace WLANBasic1009
{
    class GPS
    {
        public static SerialPort com8 = new SerialPort("COM8", 9600);
        public static String newLineRead;
        public static event EventHandler newLineAvailable;
        public static string gpsLatitude;
        public static string gpsLongitude;
        public static List<string> gpsData = new List<string>();
        public static string comPort = "COM8";
        public static bool gpsWorking = false;

        public static void onDataReveived(Object sender, SerialDataReceivedEventArgs arg)
        {
            if (com8.BytesToRead > 100)
            {
                newLineRead = com8.ReadLine();
                if (newLineRead.Contains("GPRMC") && newLineRead.Contains("A") && newLineRead.Length >= 43)
                {
                    gpsData.Clear();
                    gpsLatitude = "Latitude  :" + newLineRead.Substring(20, 11);
                    gpsLongitude = "Longitude: " + newLineRead.Substring(32, 12);
                    gpsData.Add(gpsLatitude);
                    gpsData.Add(gpsLongitude);
                    gpsWorking = true;
                    if (newLineAvailable != null) newLineAvailable(null, new EventArgs());
                }
                else
                {
                    gpsWorking = false;
                }

            }

        }

        public static void openGPSCOMPort()
        {
            try
            {
                com8.Open();
                com8.DataReceived += GPS.onDataReveived;
                gpsData.Clear();
                gpsLatitude = comPort.ToString() + " opened";
                gpsLongitude = "waiting for data";
                gpsData.Add(gpsLatitude);
                gpsData.Add(gpsLongitude);
                if (newLineAvailable != null) newLineAvailable(null, new EventArgs());
            }
            catch (Exception e)
            {
                gpsData.Clear();
                gpsLatitude = comPort.ToString() + " Error";
                gpsLongitude = "check settings";
                gpsData.Add(gpsLatitude);
                gpsData.Add(gpsLongitude);
                if (newLineAvailable != null) newLineAvailable(null, new EventArgs());
            }
        }

        public GPS()
        {
            /*    //com8.NewLine = "\n";
                try
                {
                    com8.Open();
                    com8.DataReceived += GPS.onDataReveived;
                }
                catch (Exception e)
                {
                    newLineRead = "Error";
                }*/



        }

        public static List<string> getNewLine()
        {
            return gpsData;
        }
        ~GPS()
        {
            com8.Close();
        }

        public static void closeGPSport()
        {
            gpsWorking = false;
            com8.Close();
        }

    }
}
