Untitled

mail@pastecode.io avatar
unknown
plain_text
2 years ago
56 kB
0
Indexable
Never
using GMap.NET;
using GMap.NET.MapProviders;
using GMap.NET.WindowsPresentation;
using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.IO;
using System.Threading;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using System.Windows.Threading;

namespace HSI
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public List<String> Heartbeats = new List<string>();
        private List<Drone> Drones = new List<Drone>();
        private List<Mission> Missions = new List<Mission>();
        private List<Swarm> Swarms = new List<Swarm>();
        private List<Zone> MissionZones = new List<Zone>();
        private List<Zone> SwarmZones = new List<Zone>(); 
        public delegate void UpdateTextCallback(GMapMarker marker);
        
        
        private List<Zone> CurrentZones = new List<Zone>();
        //circle attributes
        private bool createCircle = false;
        private PointLatLng circleRadius = new PointLatLng();
        private PointLatLng circleCenter = new PointLatLng();
        private int selectedmission = 0;
        public int selectedswarm = 0;
        //square attributes
        private bool createSquare = false;
        private Point squareDiagonal1 = new Point();
        private List<PointLatLng> squarecoordinates = new List<PointLatLng>();
        //polygon attributes
        private bool createPolygon = false;
        private List<PointLatLng> polygonPoints = new List<PointLatLng>();
        //swarm attribtues
        private bool createSwarm;
        private PointLatLng swarmCenter = new PointLatLng();
        private PointLatLng swarmRadius = new PointLatLng();
        private List<int> SelectedDrones = new List<int>();
        private int currentfocusedMission = 0;
        private Drone CurrentFocusedDrone = new Drone();
        private List<Status> droneTypeActive = new List<Status>();
        private List<Status> droneStatusActive = new List<Status>();
        private List<Status> swarmStatusActive = new List<Status>();
        public DispatcherTimer markerstimer = new DispatcherTimer();



        /// <summary>
        /// //////////////////////////////////////////
        public int counter = 0;
        public List<PointLatLng> route = new List<PointLatLng>();
        public List<PointLatLng> totalpath = new List<PointLatLng>()
       { new PointLatLng(33.642142, 72.993813)
        ,new PointLatLng(33.642682,72.994060)
        ,new PointLatLng(33.643334, 72.994194)
        ,new PointLatLng(33.644147, 72.994092)
        ,new PointLatLng(33.645049, 72.993685)
        ,new PointLatLng(33.645184, 72.993596)
        ,new PointLatLng(33.645720, 72.993126)
        ,new PointLatLng(33.646117, 72.992630)
        ,new PointLatLng(33.646408, 72.992206)
        ,new PointLatLng(33.646754, 72.991595)
        ,new PointLatLng(33.647031, 72.990798)
        ,new PointLatLng(33.647243, 72.989795)};
        List<PointLatLng> p = new List<PointLatLng>();
        public DispatcherTimer timer1 = new DispatcherTimer();
        public int heartbeatcounter = 0;
        /// </summary>
        public MainWindow()
        {
            InitializeComponent();
        }
        private void Close_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            this.Close();
        }

        private void runheartbeatloop(object sender, EventArgs e)
        {
            loadheartbeats(heartbeatcounter);
            heartbeatcounter++;
        }
        private void loadheartbeats(int id)
        {
            for (var a=0; a<Drones.Count; a++)
            {
                 string[] hb = Heartbeats[id].Split(',');
                if(Drones[a].Id == Convert.ToInt32(hb[0])){
                    var targetflag = false;
                    if(hb[9] == "false")
                    {
                        targetflag = false;
                    }
                    else
                    {
                        targetflag = true;
                    }

                    Drones[a].UpdateHeartBeat(Convert.ToInt32(hb[0]), Convert.ToDecimal(hb[1]), Convert.ToDecimal(hb[2]), Convert.ToDecimal(hb[3]), Convert.ToDecimal(hb[4]), Convert.ToDecimal(hb[5]), Convert.ToDecimal(hb[6]), Convert.ToDecimal(hb[7]), Convert.ToInt32(hb[8]), targetflag, Convert.ToDecimal(hb[10]), Convert.ToDecimal(hb[11]), Convert.ToDecimal(hb[12]));
                    Drones[a].ToLatLon(Convert.ToDouble(hb[1]), Convert.ToDouble(hb[2]), "42S",out Drones[a].latitude,out Drones[a].longitude);
                    gmapcontrol.Markers.Clear();
                    displayMarkers();
                }
            }
        }
        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            
            gmapcontrol.MapProvider = GoogleMapProvider.Instance;
            gmapcontrol.Zoom = 16;
            gmapcontrol.DragButton = MouseButton.Left;
            gmapcontrol.Position = new PointLatLng(33.642131, 72.993821);
            LoadDrones();
            LoadSwarms();
            DroneStatusGet();
            droneTypeGet();
            swarmStatusGet();
            loadheatbeatdatafromDatabase();
            displayMarkers();
            markerstimer.Tick += new EventHandler(runheartbeatloop);
            markerstimer.Interval = TimeSpan.FromMilliseconds(500);
            markerstimer.Start();

        }
        public class MySynchronizationContext : SynchronizationContext
        {
            public override void Post(SendOrPostCallback d, object state)
            {
                Thread t = new Thread(d.Invoke);
                t.SetApartmentState(ApartmentState.STA);
                t.Start(state);
            }
        }

        private void displayMarkers()
        {
            for (var b = 0; b < Drones.Count; b++)
            {
                if (Drones[b].latitude != 0)
                {
                    string currentDir = Directory.GetCurrentDirectory();
                    PointLatLng point = new PointLatLng(Drones[b].latitude, Drones[b].longitude);
                    GMapMarker m = new GMapMarker(point)
                    {
                        Shape = new Image
                        {
                            Width = 20,
                            Height = 20,
                            Source = new BitmapImage(new Uri(@"" + currentDir + "\\black-arrowhead-pointing-up.png")),
                            Cursor = Cursors.Hand
                        }
                    };
                    Drone D = Drones[b];
                    void mouseButtonEventHandler4(object s, MouseButtonEventArgs MouseButtonEventArgs)
                    {
                        Marker_MouseLeftButtonDown(s, MouseButtonEventArgs, D);
                    }
                    m.Shape.MouseLeftButtonUp += mouseButtonEventHandler4;
                    Application.Current.Dispatcher.BeginInvoke(new Action(() => this.gmapcontrol.Markers.Add(m)));
                    gmapcontrol.Markers.Add(m);
                    
                    
                }
            }
            if (showzonesbutton.IsChecked == true)
            {
                for (var a = 0; a < CurrentZones.Count; a++)
                {
                    createZones(CurrentZones[a]);
                }
            }
        }
        private void Image_MouseLeftButtonDown(object sender, EventArgs e)
        {

            int total = totalpath.Count - 1;
            if (counter < total)
            {
                Drone_Movements();
            }
        }
        private void Drone_Movements()
        {
            p.Add(totalpath[counter]);
            GMapRoute gmRoute = new GMapRoute(p);
            gmRoute.RegenerateShape(gmapcontrol);
            counter++;
            gmapcontrol.Markers.Clear();
            gmapcontrol.Markers.Add(gmRoute);
            string currentDir = System.IO.Directory.GetCurrentDirectory();
            int index = counter - 1;
            GMapMarker marker = new GMapMarker(totalpath[index])
            {
                Shape = new Image
                {
                    Width = 16,
                    Height = 16,
                    Source = new BitmapImage(new Uri(@"" + currentDir + "\\black-arrowhead-pointing-up.png")),
                    HorizontalAlignment = HorizontalAlignment.Right,
                    VerticalAlignment = VerticalAlignment.Bottom
                }
            };

            gmapcontrol.Markers.Add(marker);
        }
        private void UpdateText(GMapMarker m)
        {
            gmapcontrol.Markers.Add(m);
        }
        private void Marker_MouseLeftButtonDown(object sender, MouseButtonEventArgs e, Drone drone)
        {
            Dcode.Content = "Drone - " + drone.code;
            CurrentFocusedDrone = new Drone();
            CurrentFocusedDrone = drone;
            Dspeed.Content = drone.speed + "km/h";
            Dendurance.Content = drone.endurance + "Hours";
            Daltitude.Content = drone.altitude + "m/s";
            Dlatitude.Content = drone.latitude;
            Dlongitude.Content = drone.longitude;
            menu.Height = 0;
            missionlist.Height = 0;
            swarmlist.Height = 0;
            droneDetail.Height = 900;
            dronelist.Height = 0;
            displayMarkers();
            DrawerHost.IsLeftDrawerOpen = true;
        }

            private void Slider_ValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e)
        {
            gmapcontrol.Zoom = Convert.ToInt32(e.NewValue);
        }

        private void MapLayer_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            if (gmapcontrol.MapProvider == GoogleMapProvider.Instance)
            {
                gmapcontrol.MapProvider = BingSatelliteMapProvider.Instance;
                
            }
            else
            {
                gmapcontrol.MapProvider = GoogleMapProvider.Instance;
            }

        }

        private void AddMission_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            menu.Height = 0;
            dronelist.Height = 0;
            swarmlist.Height = 0;
            missionlist.Height = 900;
        }

        private void swarmlistbutton_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            menu.Height = 0;
            dronelist.Height = 0;
            missionlist.Height = 0;
            swarmlist.Height = 900;
        }

        private void dronelistbutton_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            menu.Height = 0;
            missionlist.Height = 0;
            swarmlist.Height = 0;
            dronelist.Height = 900;
        }

        private void closeMenu_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            menu.Height = 900;
            missionlist.Height = 0;
            swarmlist.Height = 0;
            dronelist.Height = 0;
            droneDetail.Height = 0;
            swarmDetail.Height = 0;
        }
        //enable user to create a circle shaped zone on the map

        private void ZoneCircle_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            if (currentfocusedMission == 0)
            {
                SwarmSelection w = new SwarmSelection();
                w.Owner = this;
                w.Show();
            }
            createCircle = true;
            gmapcontrol.DragButton = MouseButton.Middle;
        }
        //enable user to create a square shaped zone on the map
        private void ZoneSquare_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            if (currentfocusedMission == 0)
            {
                MissionSelection w = new MissionSelection();
                w.Owner = this;
                w.Show();
            }
            createSquare = true;
            gmapcontrol.DragButton = MouseButton.Middle;
        }
        //enable user to create a polygon shaped zone on the map
        private void ZonePolygon_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            if (currentfocusedMission == 0)
            {
                MissionSelection w = new MissionSelection();
                w.Owner = this;
                w.Show();
            }
            createPolygon = true;
            gmapcontrol.DragButton = MouseButton.Middle;
        }
        private void gmapcontrol_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            double lat1 = gmapcontrol.FromLocalToLatLng((int)e.GetPosition(gmapcontrol).X, (int)e.GetPosition(gmapcontrol).Y).Lat;
            double lng1 = gmapcontrol.FromLocalToLatLng((int)e.GetPosition(gmapcontrol).X, (int)e.GetPosition(gmapcontrol).Y).Lng;
            if (createPolygon)
            {
                polygonPoints.Add(new PointLatLng(lat1, lng1));
            //    gmapcontrol.Markers.Clear();
                GMapRoute gmRoute = new GMapRoute(polygonPoints);
                gmRoute.RegenerateShape(gmapcontrol);
                gmapcontrol.Markers.Add(gmRoute);
            }
            else if (createCircle)
            {
                circleCenter = new PointLatLng(lat1, lng1);

            }
            else if (createSquare)
            {
                squareDiagonal1 = new Point(lat1, lng1);
            }
            else if (createSwarm)
            {
                swarmCenter = new PointLatLng(lat1, lng1);
            }
        }

        private void gmapcontrol_MouseMove(object sender, MouseEventArgs e)
        {
            if (e.LeftButton == MouseButtonState.Pressed)
            {
                if (createCircle == true)
                {
                    gmapcontrol.Markers.Clear();
                    double lat1 = gmapcontrol.FromLocalToLatLng((int)e.GetPosition(gmapcontrol).X, (int)e.GetPosition(gmapcontrol).Y).Lat;
                    double lng1 = gmapcontrol.FromLocalToLatLng((int)e.GetPosition(gmapcontrol).X, (int)e.GetPosition(gmapcontrol).Y).Lng;

                    circleRadius = new PointLatLng(lat1, lng1);

                    double distances = distance(circleCenter.Lat, circleCenter.Lng, circleRadius.Lat, circleRadius.Lng, 'M');
                    List<PointLatLng> gpollist = new List<PointLatLng>();

                    double seg = Math.PI * 2 / 1200;
                    for (int i = 0; i < 1200; i++)
                    {
                        double theta = seg * i;
                        double a = circleCenter.Lat + Math.Cos(theta) * distances;
                        double b = circleCenter.Lng + Math.Sin(theta) * distances;

                        PointLatLng gpoi = new PointLatLng(a, b);

                        gpollist.Add(gpoi);
                    }
                    GMapPolygon gpol = new GMapPolygon(gpollist);
                    gpol.RegenerateShape(gmapcontrol);
                    (gpol.Shape as System.Windows.Shapes.Path).Stroke = Brushes.Green;
                    (gpol.Shape as System.Windows.Shapes.Path).StrokeThickness = 1.5;
                    (gpol.Shape as System.Windows.Shapes.Path).Effect = null;
                    gmapcontrol.Markers.Add(gpol);
                }
                else if (createSquare == true)
                {
                    gmapcontrol.Markers.Clear();
                    double lat = gmapcontrol.FromLocalToLatLng((int)e.GetPosition(gmapcontrol).X, (int)e.GetPosition(gmapcontrol).Y).Lat;
                    double lng = gmapcontrol.FromLocalToLatLng((int)e.GetPosition(gmapcontrol).X, (int)e.GetPosition(gmapcontrol).Y).Lng;
                    double x1 = squareDiagonal1.X;
                    double y1 = squareDiagonal1.Y;    // First diagonal point
                    double x2 = lat;
                    double y2 = lng;    // Second diagonal point

                    var xc = (x1 + x2) / 2;
                    var yc = (y1 + y2) / 2;    // Center point
                    var xd = (x1 - x2) / 2;
                    var yd = (y1 - y2) / 2;    // Half-diagonal

                    var x3 = xc - yd;
                    var y3 = yc + xd;    // Third corner
                    var x4 = xc + yd;
                    var y4 = yc - xd;
                    PointLatLng corner1 = new PointLatLng(x3, y3);
                    PointLatLng corner2 = new PointLatLng(x1, y1);
                    PointLatLng corner3 = new PointLatLng(x4, y4);
                    PointLatLng corner4 = new PointLatLng(x2, y2);
                    List<PointLatLng> squarepoints = new List<PointLatLng>();
                    squarepoints.Add(corner1);
                    squarepoints.Add(corner2);
                    squarepoints.Add(corner3);
                    squarepoints.Add(corner4);
                    squarecoordinates = squarepoints;
                    GMapPolygon square = new GMapPolygon(squarepoints);
                    square.RegenerateShape(gmapcontrol);
                    (square.Shape as System.Windows.Shapes.Path).Stroke = Brushes.Green;
                    (square.Shape as System.Windows.Shapes.Path).StrokeThickness = 1.5;
                    square.Shape.OpacityMask = Brushes.DarkRed;
                    (square.Shape as System.Windows.Shapes.Path).Effect = null;
                    gmapcontrol.Markers.Add(square);

                }
                if (createSwarm == true)
                {
                    gmapcontrol.Markers.Clear();
                    displayMarkers();
                    double lat1 = gmapcontrol.FromLocalToLatLng((int)e.GetPosition(gmapcontrol).X, (int)e.GetPosition(gmapcontrol).Y).Lat;
                    double lng1 = gmapcontrol.FromLocalToLatLng((int)e.GetPosition(gmapcontrol).X, (int)e.GetPosition(gmapcontrol).Y).Lng;

                    swarmRadius = new PointLatLng(lat1, lng1);

                    double distances = distance(swarmCenter.Lat, swarmCenter.Lng, swarmRadius.Lat, swarmRadius.Lng, 'M');
                    List<PointLatLng> gpollist = new List<PointLatLng>();

                    double seg = Math.PI * 2 / 1200;
                    for (int i = 0; i < 1200; i++)
                    {
                        double theta = seg * i;
                        double a = swarmCenter.Lat + Math.Cos(theta) * distances;
                        double b = swarmCenter.Lng + Math.Sin(theta) * distances;

                        PointLatLng gpoi = new PointLatLng(a, b);

                        gpollist.Add(gpoi);
                    }
                    GMapPolygon gpol = new GMapPolygon(gpollist);
                    gpol.RegenerateShape(gmapcontrol);
                    (gpol.Shape as System.Windows.Shapes.Path).Stroke = Brushes.Green;
                    (gpol.Shape as System.Windows.Shapes.Path).StrokeThickness = 1.5;
                    (gpol.Shape as System.Windows.Shapes.Path).Opacity = 0.5;
                    (gpol.Shape as System.Windows.Shapes.Path).Effect = null;
                    gmapcontrol.Markers.Add(gpol);
                }
            }
            else
            {
                if (createCircle)
                {
                    if (!circleRadius.IsEmpty)
                    {
                        ZoneModal zone = new ZoneModal();
                        zone.zonecoords = circleCenter.Lat.ToString() + ",";
                        zone.zonecoords += circleCenter.Lng.ToString() + ",";
                        zone.zonecoords += circleRadius.Lat.ToString() + ",";
                        zone.zonecoords += circleRadius.Lng.ToString();
                        zone.shape = 7;
                        zone.mission_ID = selectedmission;
                        zone.swarm_ID = selectedswarm;
                        zone.Show();
                        createCircle = false;
                        createSquare = false;
                        createSwarm = false;
                        gmapcontrol.DragButton = MouseButton.Left;
                        gmapcontrol.Markers.Clear();
                        displayMarkers();
                    }
                }
                else if (createSwarm)
                {
                    if (!swarmRadius.IsEmpty)
                    {
                        double distances = distance(swarmCenter.Lat, swarmCenter.Lng, swarmRadius.Lat, swarmRadius.Lng, 'M');
                        SwarmModal sm = new SwarmModal();
                        for (var b = 0; b < Drones.Count; b++)
                        {
                            PointLatLng droneposition = new PointLatLng(Drones[b].latitude, Drones[b].longitude);
                            double markerdistance = distance(swarmCenter.Lat, swarmCenter.Lng, droneposition.Lat, droneposition.Lng, 'M');
                            if (markerdistance < distances)
                            {
                                sm.selectedDrones.Add(Drones[b].Id);
                            }
                        }
                        sm.Show();
                        createCircle = false;
                        createSwarm = false;
                        createPolygon = false;
                        createSquare = false;
                        gmapcontrol.DragButton = MouseButton.Left;
                        gmapcontrol.Markers.Clear();
                        displayMarkers();
                    }
                }
                else if (createSquare)
                {
                    if (squarecoordinates.Count != 0)
                    {
                        ZoneModal zone = new ZoneModal();
                        zone.zonecoords = squarecoordinates[0].Lat.ToString() + ",";
                        zone.zonecoords += squarecoordinates[0].Lng.ToString() + ",";
                        zone.zonecoords += squarecoordinates[1].Lat.ToString() + ",";
                        zone.zonecoords += squarecoordinates[1].Lng.ToString() + ",";
                        zone.zonecoords += squarecoordinates[2].Lat.ToString() + ",";
                        zone.zonecoords += squarecoordinates[2].Lng.ToString() + ",";
                        zone.zonecoords += squarecoordinates[3].Lat.ToString() + ",";
                        zone.zonecoords += squarecoordinates[3].Lng.ToString();
                        zone.shape = 8;
                        zone.mission_ID = selectedmission;
                        zone.swarm_ID = selectedswarm;
                        zone.Show();
                        createCircle = false;
                        createSquare = false;
                        createSwarm = false;
                        gmapcontrol.DragButton = MouseButton.Left;
                        gmapcontrol.Markers.Clear();
                        displayMarkers();
                    }
                    
                }
            }

        }
        private void gmapcontrol_MouseDoubleClick(object sender, MouseButtonEventArgs e)
        {
            if (createPolygon)
            {
                double lat = gmapcontrol.FromLocalToLatLng((int)e.GetPosition(gmapcontrol).X, (int)e.GetPosition(gmapcontrol).Y).Lat;
                double lng = gmapcontrol.FromLocalToLatLng((int)e.GetPosition(gmapcontrol).X, (int)e.GetPosition(gmapcontrol).Y).Lng;
                string point = lat + "," + lng;
                gmapcontrol.Markers.Clear();
                polygonPoints.Add(new PointLatLng(lat, lng));
                GMapPolygon polygon = new GMapPolygon(polygonPoints);
                polygon.RegenerateShape(gmapcontrol);
                (polygon.Shape as System.Windows.Shapes.Path).Stroke = Brushes.Green;
                (polygon.Shape as System.Windows.Shapes.Path).StrokeThickness = 1.5;
                gmapcontrol.Markers.Add(polygon); ZoneModal zone = new ZoneModal();
                for(var a=0; a< polygonPoints.Count-1; a++)
                {
                    zone.zonecoords += polygonPoints[a].Lat.ToString() + ",";
                    zone.zonecoords += polygonPoints[a].Lng.ToString() + ",";
                }
                zone.zonecoords += polygonPoints[polygonPoints.Count - 1].Lat.ToString() + ",";
                zone.zonecoords += polygonPoints[polygonPoints.Count - 1].Lng.ToString();
                zone.shape = 9;
                zone.mission_ID = selectedmission;
                zone.swarm_ID = selectedswarm;
              //  zone.Show();
                createCircle = false;
                createSquare = false;
                createSwarm = false;
               // gmapcontrol.Markers.Clear();
                //displayMarkers();
                createPolygon = false;
            }

        }

        private void loadheatbeatdatafromDatabase()
        {
            SqlDataReader reader;
            string connetionString = @"Server=localhost\SQLEXPRESS;Database=HSIv2;Trusted_Connection=True;";
            SqlConnection cnn = new SqlConnection(connetionString);
            cnn.Open();
            string sql = "Select * from HEARTBEAT";
            SqlCommand cmd = new SqlCommand(sql, cnn);
            reader = cmd.ExecuteReader();
            while (reader.Read())
            {
                string ss = ((int)reader.GetValue(0)).ToString() + "," + (decimal)reader.GetValue(1) + "," + (decimal)reader.GetValue(2) + "," + (decimal)reader.GetValue(3) + "," + (decimal)reader.GetValue(4) + "," + (decimal)reader.GetValue(5) + "," + (decimal)reader.GetValue(6) + "," + (decimal)reader.GetValue(7) + "," + (int)reader.GetValue(8) + "," + (string)reader.GetValue(9) + "," + (decimal)reader.GetValue(10) + "," + (decimal)reader.GetValue(11) + "," + (decimal)reader.GetValue(12);
                Heartbeats.Add(ss);
            }
            cnn.Close();
        }

        private void LoadDrones()
        {
            try
            {
                SqlDataReader reader;
                string connetionString = @"Server=localhost\SQLEXPRESS;Database=HSIv2;Trusted_Connection=True;";
                SqlConnection cnn = new SqlConnection(connetionString);
                cnn.Open();
                string sql = "Select * from DRONE";
                SqlCommand cmd = new SqlCommand(sql, cnn);
                reader = cmd.ExecuteReader();
                while (reader.Read())
                {
                    Drone d = new Drone();
                    d.Id = (int)reader.GetValue(0);
                    d.code = (string)reader.GetValue(1);
                    d.type = (int)reader.GetValue(2);
                    d.iscamera = (string)reader.GetValue(3);
                    d.cameraRange = (decimal)reader.GetValue(4);
                    d.ispayload = (string)reader.GetValue(5);
                    d.payload_value = (decimal)reader.GetValue(6);
                    d.altitude = (decimal)reader.GetValue(7);
                    d.endurance = (int)reader.GetValue(8);
                    d.speed = (decimal)reader.GetValue(9);
                    d.status = (int)reader.GetValue(10);
                    d.latitude = Convert.ToDouble((decimal)reader.GetValue(11));
                    d.longitude = Convert.ToDouble((decimal)reader.GetValue(12));
                    Drones.Add(d);
                    Label l = new Label()
                    {
                        Margin = new Thickness(8, 19, 27, 2),
                        Width = 150,
                        Height = 34,
                        Content = "Drone - "+d.code,
                        FontSize = 12,
                        Foreground = Brushes.White,
                        Cursor = Cursors.Hand
                    };
                l.MouseLeftButtonDown += L_MouseLeftButtonDown;
                dronelist.Children.Add(l);
                }
                cnn.Close();
            }
            catch (Exception e)
            {
                MessageBox.Show(e.ToString());
            }
        }
        private void LoadMissions()
        {
            try
            {
                SqlDataReader reader;
                string connetionString = @"Server=localhost\SQLEXPRESS;Database=HSIv2;Trusted_Connection=True;";
                SqlConnection cnn = new SqlConnection(connetionString);
                cnn.Open();
                string sql = "Select * from SWARM";
                SqlCommand cmd = new SqlCommand(sql, cnn);
                reader = cmd.ExecuteReader();
                while (reader.Read())
                {
                    Mission S = new Mission();
                   // S.miss = (int)reader.GetValue(0);
                   // S.mission_ID = (int)reader.GetValue(1);
                   // S.swarm_STATUS = (int)reader.GetValue(2);
                  //  S.swarm_CODE = "Swarm - " + (int)reader.GetValue(0);
                    Label l = new Label()
                    {
                        Margin = new Thickness(0, 5, 0, 0),
                        Width = 150,
                        Height = 30,
                        Content = "anything", //S.swarm_CODE,
                        FontSize = 16,
                        Foreground = Brushes.White,
                        Cursor = Cursors.Hand
                    };
                    l.MouseLeftButtonDown += L_MouseLeftButtonDown1;
                   // Swarms.Add(S);
                    swarmslisted.Items.Add(l);
                }
                cnn.Close();
            }
            catch (Exception e)
            {
                MessageBox.Show(e.ToString());
            }
        }
        private void LoadSwarms()
        {
            try
            {
                SqlDataReader reader;
                string connetionString = @"Server=localhost\SQLEXPRESS;Database=HSIv2;Trusted_Connection=True;";
                SqlConnection cnn = new SqlConnection(connetionString);
                cnn.Open();
                string sql = "Select * from SWARM";
                SqlCommand cmd = new SqlCommand(sql, cnn);
                reader = cmd.ExecuteReader();
                while (reader.Read())
                {
                    Swarm S = new Swarm();
                    S.swarm_ID = (int)reader.GetValue(0);
                    S.mission_ID = (int)reader.GetValue(1);
                    S.swarm_STATUS = (int)reader.GetValue(2);
                    S.swarm_CODE = "Swarm - " + (int)reader.GetValue(0);
                    Label l = new Label()
                    {
                        Margin = new Thickness(0, 5, 0, 0),
                        Width = 150,
                        Height = 30,
                        Content = S.swarm_CODE,
                        FontSize = 16,
                        Foreground = Brushes.White,
                        Cursor = Cursors.Hand
                    };
                    l.MouseLeftButtonDown += L_MouseLeftButtonDown1;
                    Swarms.Add(S);
                    swarmslisted.Items.Add(l);
                }
                cnn.Close();
            }
            catch (Exception e)
            {
                MessageBox.Show(e.ToString());
            }
        }

        private void L_MouseLeftButtonDown1(object sender, MouseButtonEventArgs e)
        {
            Label ll = (Label)sender;
            string[] codestring = ll.Content.ToString().Split(' ');
            Scode.Content = ll.Content;
            for (var a = 0; a < Swarms.Count; a++)
            {
                if ((string)ll.Content == Swarms[a].swarm_CODE)
                {
                    if (Swarms[a].mission_ID != 0)
                    {
                        for(var b=0; b<Missions.Count; b++)
                        {
                            if(Swarms[a].mission_ID == Missions[b].Id)
                            {
                                Smission.Content = Missions[b].mission_CODE;
                            }
                            else
                            {
                                Smission.Content = "No Mission Assigned!";
                            }
                        }
                    }
                    else
                    {
                        Smission.Content = "No Mission Assigned!";
                    }
                    for(var c=0; c<swarmStatusActive.Count; c++)
                    {
                        if(Swarms[a].swarm_STATUS == swarmStatusActive[c].status_ID)
                        {
                            Sstatus.Content = swarmStatusActive[c].description;
                        }
                    }
                    try
                    {
                        SqlDataReader reader;
                        string connetionString = @"Server=localhost\SQLEXPRESS;Database=HSIv2;Trusted_Connection=True;";
                        SqlConnection cnn = new SqlConnection(connetionString);
                        cnn.Open();
                        string sql = "Select * from SWARMDRONE where swarm_ID="+codestring[2];
                        SqlCommand cmd = new SqlCommand(sql, cnn);
                        reader = cmd.ExecuteReader();
                        while (reader.Read())
                        {
                            for(var m=0; m<Drones.Count; m++)
                            {
                                if((int)reader.GetValue(1) == Convert.ToInt32(codestring[2]))
                                {
                                    Label l = new Label()
                                    {
                                        Margin = new Thickness(8, 5, 0, 0),
                                        Width = 150,
                                        Height = 30,
                                        Content = "Drone - " + Drones[m].code,
                                        FontSize = 12,
                                        Foreground = Brushes.White,
                                        Cursor = Cursors.Hand
                                    };
                                    l.MouseLeftButtonDown += L_MouseLeftButtonDown1;
                                    Sdroneslist.Items.Add(l);
                                }
                            }
                            
                        }
                        cnn.Close();
                    }
                    catch (Exception j)
                    {
                        notification mn = new notification();
                        mn.content = "Some Problem Occured While Fetching Drones List From Database!";
                        mn.Show();
                        var timer = new DispatcherTimer { Interval = TimeSpan.FromSeconds(2) };
                        timer.Start();
                        timer.Tick += (s, args) =>
                        {
                            timer.Stop();
                            mn.Close();
                        };
                    }

                }
            }
            menu.Height = 0;
            missionlist.Height = 0;
            swarmlist.Height = 0;
            swarmDetail.Height = 900;
            droneDetail.Height = 0;
            dronelist.Height = 0;
        }

        private void L_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            Label ll = (Label)sender;
            string[] codestring = ll.Content.ToString().Split(' ');
            Dcode.Content = "Drone - " + codestring[2];
            CurrentFocusedDrone = new Drone();
            for(var a=0; a<Drones.Count; a++)
            {
                if(codestring[2] == Drones[a].code)
                {
                    CurrentFocusedDrone = Drones[a];
                    Dspeed.Content = Drones[a].speed + "km/h";
                    Dendurance.Content = Drones[a].endurance + "Hours";
                    Daltitude.Content = Drones[a].altitude + "m/s";
                }
            }
            menu.Height = 0;
            missionlist.Height = 0;
            swarmlist.Height = 0;
            droneDetail.Height = 900;
            dronelist.Height = 0;
        }

        private void LoadMissionSpecificZones()
        {
            try
            {
                SqlDataReader reader;
                string connetionString = @"Server=localhost\SQLEXPRESS;Database=HSIv2;Trusted_Connection=True;";
                SqlConnection cnn = new SqlConnection(connetionString);
                cnn.Open();
                string sql = "Select * from ZONES where mission_ID="+selectedmission;
                SqlCommand cmd = new SqlCommand(sql, cnn);
                reader = cmd.ExecuteReader();
                while (reader.Read())
                {
                    Zone z = new Zone();
                    z.zone_ID = (int)reader.GetValue(0);
                    z.mission_ID = (int)reader.GetValue(2);
                    z.swarm_ID = (int)reader.GetValue(3);
                    z.zone_SHAPE = (int)reader.GetValue(4);
                    z.zone_COORDINATES = (string)reader.GetValue(5);
                    MissionZones.Add(z);
                }
                cnn.Close();
            }
            catch (Exception e)
            {
                MessageBox.Show(e.ToString());
            }
        }
        public void LoadSwarmSpecificZones()
        {
            try
            {
                SqlDataReader reader;
                string connetionString = @"Server=localhost\SQLEXPRESS;Database=HSIv2;Trusted_Connection=True;";
                SqlConnection cnn = new SqlConnection(connetionString);
                cnn.Open();
                string sql = "Select * from ZONES where swarm_ID="+selectedswarm;
                SqlCommand cmd = new SqlCommand(sql, cnn);
                reader = cmd.ExecuteReader();
                while (reader.Read())
                {
                    Zone z = new Zone();
                    z.zone_ID = (int)reader.GetValue(0);
                    z.mission_ID = (int)reader.GetValue(2);
                    z.swarm_ID = (int)reader.GetValue(3);
                    z.zone_SHAPE = (int)reader.GetValue(4);
                    z.zone_COORDINATES = (string)reader.GetValue(5);
                    z.zone_STATUS = (string)reader.GetValue(6);
                    SwarmZones.Add(z);
                    createZones(z);
                }
                cnn.Close();

                CurrentZones = SwarmZones;
                notification mn = new notification();
                mn.content = "Swarm Specific Zones Loaded on the Map!";
                mn.Show();
                var timer = new DispatcherTimer { Interval = TimeSpan.FromSeconds(2) };
                timer.Start();
                timer.Tick += (s, args) =>
                {
                    timer.Stop();
                    mn.Close();
                };
            }
            catch (Exception e)
            {
                MessageBox.Show(e.ToString());
                notification mn = new notification();
                mn.content = "Zones Not Loaded Due to Some Unknown Error!";
                mn.Show();
                var timer = new DispatcherTimer { Interval = TimeSpan.FromSeconds(2) };
                timer.Start();
                timer.Tick += (s, args) =>
                {
                    timer.Stop();
                    mn.Close();
                };
            }
        }
        private double distance(double lat1, double lon1, double lat2, double lon2, char unit)
        {
            if ((lat1 == lat2) && (lon1 == lon2))
            {
                return 0;
            }
            else
            {
                double theta = lon1 - lon2;
                double dist = Math.Sin(deg2rad(lat1)) * Math.Sin(deg2rad(lat2)) + Math.Cos(deg2rad(lat1)) * Math.Cos(deg2rad(lat2)) * Math.Cos(deg2rad(theta));
                dist = Math.Acos(dist);
                dist = dist * 60 * 1.1515;
                if (unit == 'K')
                {
                    dist *= 1.609344;
                }
                else if (unit == 'N')
                {
                    dist *= 0.8684;
                }
                return dist;
            }
        }

        private double deg2rad(double deg)
        {
            return deg * Math.PI / 180.0;
        }

        private double rad2deg(double rad)
        {
            return rad / Math.PI * 180.0;
        }

        private void droneTypeGet()
        {
            try
            {
                SqlDataReader reader;
                string connetionString = @"Server=localhost\SQLEXPRESS;Database=HSIv2;Trusted_Connection=True;";
                SqlConnection cnn = new SqlConnection(connetionString);
                cnn.Open();
                string sql = "Select * from STATURE WHERE entity='DRONETYPE'";
                SqlCommand cmd = new SqlCommand(sql, cnn);
                reader = cmd.ExecuteReader();
                while (reader.Read())
                {
                    Status s = new Status();
                    s.status_ID = (int)reader.GetValue(0);
                    s.entity = (string)reader.GetValue(1);
                    s.description = (string)reader.GetValue(2);
                    droneTypeActive.Add(s);
                }
                cnn.Close();
            }
            catch (Exception e)
            {
                MessageBox.Show(e.ToString());
            }
        }
        private void swarmStatusGet()
        {
            try
            {
                SqlDataReader reader;
                string connetionString = @"Server=localhost\SQLEXPRESS;Database=HSIv2;Trusted_Connection=True;";
                SqlConnection cnn = new SqlConnection(connetionString);
                cnn.Open();
                string sql = "Select * from STATURE WHERE entity='SWARMSTATUS'";
                SqlCommand cmd = new SqlCommand(sql, cnn);
                reader = cmd.ExecuteReader();
                while (reader.Read())
                {
                    Status s = new Status();
                    s.status_ID = (int)reader.GetValue(0);
                    s.entity = (string)reader.GetValue(1);
                    s.description = (string)reader.GetValue(2);
                    swarmStatusActive.Add(s);
                }
                cnn.Close();
            }
            catch (Exception e)
            {
                MessageBox.Show(e.ToString());
            }
        }
        private void DroneStatusGet()
        {
            try
            {
                SqlDataReader reader;
                string connetionString = @"Server=localhost\SQLEXPRESS;Database=HSIv2;Trusted_Connection=True;";
                SqlConnection cnn = new SqlConnection(connetionString);
                cnn.Open();
                string sql = "Select * from STATURE WHERE entity='DRONESTATUS'";
                SqlCommand cmd = new SqlCommand(sql, cnn);
                reader = cmd.ExecuteReader();
                while (reader.Read())
                {
                    Status s = new Status();
                    s.status_ID = (int)reader.GetValue(0);
                    s.entity = (string)reader.GetValue(1);
                    s.description = (string)reader.GetValue(2);
                    droneStatusActive.Add(s);
                }
                cnn.Close();
            }
            catch (Exception e)
            {
                MessageBox.Show(e.ToString());
            }
        }
        public void showNotification()
        {
        }

        private void WrapPanel_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            MissionModal m = new MissionModal();
            m.Show();
        }

        public void readhearbeats()
        {
            string[] lines = File.ReadAllLines(@"F:\heartbeat.txt");
            foreach (string line in lines)
            {
                    string[] heartbeat_information = line.Split(',');

                var timer = new DispatcherTimer { Interval = TimeSpan.FromSeconds(5) };
                timer.Start();
                timer.Tick += (s, args) =>
                {
                    timer.Stop();
                    try
                    {
                        SqlDataAdapter adapter = new SqlDataAdapter();
                        string connetionString = @"Server=localhost\SQLEXPRESS;Database=HSIv2;Trusted_Connection=True;";
                        SqlConnection cnn = new SqlConnection(connetionString);

                        cnn.Open();
                        string sql = "INSERT INTO HEARTBEAT(UAV_ID, px, py, pz, vx, vy, vz, heading, mode, flag, tx, ty, tz) VALUES(" +  heartbeat_information[0]+ "," + heartbeat_information[1] + "," + heartbeat_information[2] + "," + heartbeat_information[3] + "," + heartbeat_information[4] + "," + heartbeat_information[5] + "," +  heartbeat_information[6] + "," + heartbeat_information[7] + "," + heartbeat_information[8] + ",'" + heartbeat_information[9] + "'," +  heartbeat_information[10] + "," + heartbeat_information[11] + "," + heartbeat_information[12] + ");";
                        adapter.InsertCommand = new SqlCommand(sql, cnn);
                        adapter.InsertCommand.ExecuteNonQuery();
                        cnn.Close();
                    }
                    catch(Exception e)
                    {
                        MessageBox.Show(e.ToString());
                    }
                };
                
            }
        }

        private void WrapPanel_MouseLeftButtonDown_1(object sender, MouseButtonEventArgs e)
        {
            MissionSelection mm = new MissionSelection();
            mm.Show();
        }

        private void WrapPanel_MouseLeftButtonDown_2(object sender, MouseButtonEventArgs e)
        {
            ZoneModal newzone = new ZoneModal();
            newzone.Owner = this;
            newzone.Show();
        }

        private void WrapPanel_MouseLeftButtonDown_3(object sender, MouseButtonEventArgs e)
        {
            DroneModal newdrone = new DroneModal();
            newdrone.Owner = this;
            newdrone.Show();
        }

        private void AddSwarmButton_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            SwarmModal sm = new SwarmModal();
            sm.Owner = this;
            sm.Show();
        }

        private void createZones(Zone z)
        {
            if(z.zone_SHAPE == 7)
            {
                string[] coordinates = z.zone_COORDINATES.Split(',');
                PointLatLng cstart = new PointLatLng(Convert.ToDouble(coordinates[0]), Convert.ToDouble(coordinates[1]));
                PointLatLng cend = new PointLatLng(Convert.ToDouble(coordinates[2]), Convert.ToDouble(coordinates[3]));
                double distances = distance(cstart.Lat, cstart.Lng, cend.Lat, cend.Lng, 'M');
                List<PointLatLng> gpollist = new List<PointLatLng>();

                double seg = Math.PI * 2 / 1000;

                for (int i = 0; i < 1000; i++)
                {
                    double theta = seg * i;
                    double point1 = cstart.Lat + Math.Cos(theta) * distances;
                    double point2 = cstart.Lng + Math.Sin(theta) * distances;

                    PointLatLng gpoi = new PointLatLng(point1, point2);

                    gpollist.Add(gpoi);
                }
                GMapPolygon gpol = new GMapPolygon(gpollist);
                gpol.RegenerateShape(gmapcontrol);
                if (z.zone_STATUS == "Loiter")
                {
                    (gpol.Shape as System.Windows.Shapes.Path).Stroke = Brushes.Coral;
                    (gpol.Shape as System.Windows.Shapes.Path).Fill = Brushes.Coral;
                }
                else if (z.zone_STATUS == "No Fly")
                {
                    (gpol.Shape as System.Windows.Shapes.Path).Stroke = Brushes.Red;
                    (gpol.Shape as System.Windows.Shapes.Path).Fill = Brushes.Red;
                }
                else if (z.zone_STATUS == "Landing")
                {
                    (gpol.Shape as System.Windows.Shapes.Path).Stroke = Brushes.Green;
                    (gpol.Shape as System.Windows.Shapes.Path).Fill = Brushes.Green;
                }
                else if (z.zone_STATUS == "Takeoff")
                {
                    (gpol.Shape as System.Windows.Shapes.Path).Stroke = Brushes.Yellow;
                    (gpol.Shape as System.Windows.Shapes.Path).Fill = Brushes.Yellow;
                }
                (gpol.Shape as System.Windows.Shapes.Path).StrokeThickness = 1.5;
                (gpol.Shape as System.Windows.Shapes.Path).Effect = null;
                gmapcontrol.Markers.Add(gpol);
            }
            else if(z.zone_SHAPE == 8)
            {
                string[] coordinates = z.zone_COORDINATES.Split(',');
                PointLatLng corner1 = new PointLatLng(Convert.ToDouble(coordinates[0]), Convert.ToDouble(coordinates[1]));
                PointLatLng corner2 = new PointLatLng(Convert.ToDouble(coordinates[2]), Convert.ToDouble(coordinates[3]));
                PointLatLng corner3 = new PointLatLng(Convert.ToDouble(coordinates[4]), Convert.ToDouble(coordinates[5]));
                PointLatLng corner4 = new PointLatLng(Convert.ToDouble(coordinates[6]), Convert.ToDouble(coordinates[7]));
                List<PointLatLng> squarepoints = new List<PointLatLng>();
                squarepoints.Add(corner1);
                squarepoints.Add(corner2);
                squarepoints.Add(corner3);
                squarepoints.Add(corner4);
                GMapPolygon square = new GMapPolygon(squarepoints);
                square.RegenerateShape(gmapcontrol); 
                if (z.zone_STATUS == "Loiter")
                {
                    (square.Shape as System.Windows.Shapes.Path).Stroke = Brushes.Coral;
                    (square.Shape as System.Windows.Shapes.Path).Fill = Brushes.Coral;
                }
                else if (z.zone_STATUS == "No Fly")
                {
                    (square.Shape as System.Windows.Shapes.Path).Stroke = Brushes.Red;
                    (square.Shape as System.Windows.Shapes.Path).Fill = Brushes.Red;
                }
                else if (z.zone_STATUS == "Landing")
                {
                    (square.Shape as System.Windows.Shapes.Path).Stroke = Brushes.Green;
                    (square.Shape as System.Windows.Shapes.Path).Fill = Brushes.Green;
                }
                else if (z.zone_STATUS == "Takeoff")
                {
                    (square.Shape as System.Windows.Shapes.Path).Stroke = Brushes.Yellow;
                    (square.Shape as System.Windows.Shapes.Path).Fill = Brushes.Yellow;
                }
                (square.Shape as System.Windows.Shapes.Path).StrokeThickness = 1.5;
                (square.Shape as System.Windows.Shapes.Path).Effect = null;
                gmapcontrol.Markers.Add(square);
            }
            else if (z.zone_SHAPE == 9)
            {
                string[] coordinates = z.zone_COORDINATES.Split(',');
                List<PointLatLng> polygoncoordinate = new List<PointLatLng>();
                for(var a=0; a<coordinates.Length; a = a + 2)
                {
                    polygoncoordinate.Add(new PointLatLng(Convert.ToDouble(coordinates[a]), Convert.ToDouble(coordinates[a + 1])));
                }
                GMapPolygon polygon = new GMapPolygon(polygoncoordinate);
                polygon.RegenerateShape(gmapcontrol);
                if (z.zone_STATUS == "Loiter")
                {
                    (polygon.Shape as System.Windows.Shapes.Path).Stroke = Brushes.Coral;
                    (polygon.Shape as System.Windows.Shapes.Path).Fill = Brushes.Coral;
                }
                else if (z.zone_STATUS == "No Fly")
                {
                    (polygon.Shape as System.Windows.Shapes.Path).Stroke = Brushes.Red;
                    (polygon.Shape as System.Windows.Shapes.Path).Fill = Brushes.Red;
                }
                else if (z.zone_STATUS == "Landing")
                {
                    (polygon.Shape as System.Windows.Shapes.Path).Stroke = Brushes.Green;
                    (polygon.Shape as System.Windows.Shapes.Path).Fill = Brushes.Green;
                }
                else if (z.zone_STATUS == "Takeoff")
                {
                    (polygon.Shape as System.Windows.Shapes.Path).Stroke = Brushes.Yellow;
                    (polygon.Shape as System.Windows.Shapes.Path).Fill = Brushes.Yellow;
                }
                (polygon.Shape as System.Windows.Shapes.Path).StrokeThickness = 1.5;
                (polygon.Shape as System.Windows.Shapes.Path).Effect = null;
                gmapcontrol.Markers.Add(polygon);
            }
        }

        private void swarmzonebutton_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            SwarmSelection S = new SwarmSelection();
            S.Owner = this;
            S.Show();
        }

        private void ToggleButton_Checked(object sender, RoutedEventArgs e)
        {
            selectedinformation.Visibility = Visibility.Hidden;
            gmapcontrol.Markers.Clear();
            displayMarkers();
        }

        private void ToggleButton_Unchecked(object sender, RoutedEventArgs e)
        {
            for (var a = 0; a < CurrentZones.Count; a++)
            {
                createZones(CurrentZones[a]);
                selectedinformation.Visibility = Visibility.Visible;
                selectedinformation.Content = "Information related to current zones here...";
            }
            displayMarkers();
        }

        private void CreateSwarmButton_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            createCircle = false;
            createSquare = false;
            createPolygon = false;
            createSwarm = true;

            gmapcontrol.DragButton = MouseButton.Middle;
        }

        private void DroneEdit_Click(object sender, RoutedEventArgs e)
        {
            DroneEdit ed = new DroneEdit();
            ed.dId = CurrentFocusedDrone.Id;
            ed.dcode = CurrentFocusedDrone.code;
            ed.dspeed = CurrentFocusedDrone.speed;
            ed.dendurance = CurrentFocusedDrone.endurance;
            ed.daltitude = CurrentFocusedDrone.altitude;
            ed.dlatitude = CurrentFocusedDrone.latitude;
            ed.dlongitude = CurrentFocusedDrone.longitude;
            ed.dtype = CurrentFocusedDrone.type;
            ed.dstatus = CurrentFocusedDrone.status;
            ed.Show();
        }
    }
}