using System;
using System.Device.Location;
using Microsoft.Phone.Controls;
using System.Windows;

namespace WPLocalisationGSM
{
    public partial class MainPage : PhoneApplicationPage
    {
        GeoCoordinateWatcher watcher;

        // Constructor
        public MainPage()
        {
            InitializeComponent();
            App.Current.Exit += Current_Exit;
            if (watcher == null)
            {
                watcher = new GeoCoordinateWatcher(GeoPositionAccuracy.Default);
                watcher.MovementThreshold = 20;
                watcher.StatusChanged += watcher_StatusChanged;
                watcher.PositionChanged += watcher_PositionChanged;
                watcher.Start();
            }
        }

        void Current_Exit(object sender, EventArgs e)
        {
            watcher.Stop();
        }

        void watcher_PositionChanged(object sender, GeoPositionChangedEventArgs<GeoCoordinate> e)
        {
            txtPosition.Text = String.Format("Längengrad: {0}\r\nBreitengrad: {1}\r\nvom: {2}",
                e.Position.Location.Longitude.ToString("0.000"),
                e.Position.Location.Latitude.ToString("0.000"),
                e.Position.Timestamp.ToString()
                );
        }

        void watcher_StatusChanged(object sender, GeoPositionStatusChangedEventArgs e)
        {
            switch (e.Status)
            {
                case GeoPositionStatus.Disabled:
                    if (watcher.Permission == GeoPositionPermission.Denied)
                    {
                        // The user has disabled the Location Service on their device.
                        txtStatus.Text = "Die Anwendung hat keinen Zugriff auf Lokationsdaten";
                    }
                    else
                    {
                        txtStatus.Text = "Auf diesem Gerät stehen keine Lokationsdaten zur Verfügung.";
                    }
                    break;

                case GeoPositionStatus.Initializing:
                    txtStatus.Text= "Gerät wird initialisiert...";
                    break;

                case GeoPositionStatus.NoData:
                    // The Location Service is working, but it cannot get location data.
                    // Alert the user and enable the Stop Location button.
                    txtStatus.Text = "Lokationsdaten nicht verfügbar";
                    break;

                case GeoPositionStatus.Ready:
                    // The Location Service is working and is receiving location data.
                    // Show the current position and enable the Stop Location button.
                    txtStatus.Text = "Lokationsdaten sind verfügbar";
                    break;
                    }
        }
    }
}