using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using System.Collections.ObjectModel;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Controls.Maps;
using GeoWindowsPhone.GeocodeService;

namespace GeoWindowsPhone
{
    public partial class MainPage : PhoneApplicationPage
    {
        GeocodeServiceClient _svc;
        public MainPage()
        {
            InitializeComponent();

            
            _svc = new GeocodeServiceClient();
            _svc.GeocodeCompleted += (s, e) =>
            {
                
                var geoResult = (from r in e.Result.Results
                                 orderby (int)r.Confidence ascending
                                 select r).FirstOrDefault();
                if (geoResult != null)
                {
                    this.SetLocation(geoResult.Locations[0].Latitude,
                        geoResult.Locations[0].Longitude,
                        10,
                        true);
                }
            };
        }

        private void SetLocation(double latitude, double longitude, double zoomLevel, bool showLocator)
        {
            
            Microsoft.Phone.Controls.Maps.Platform.Location location =
                new Microsoft.Phone.Controls.Maps.Platform.Location();
            location.Latitude = latitude;
            location.Longitude = longitude;
            bingMap.SetView(location, zoomLevel);
            bingMapLocator.Location = location;
            if (showLocator)
            {
                locator.Visibility = Visibility.Visible;
            }
            else
            {
                locator.Visibility = Visibility.Collapsed;
            }
        }

        private void btnPlot_Click(object sender, RoutedEventArgs e)
        {
            GeocodeService.GeocodeRequest request =
                new GeocodeService.GeocodeRequest();
 
            // Only accept results with high confidence.
            request.Options = new GeocodeOptions()
            {
                Filters = new ObservableCollection<FilterBase>
                {
                    new ConfidenceFilter()
                    {
                        MinimumConfidence = Confidence.High
                    }
                }
            };
 
            request.Credentials = new Credentials()
            {
                ApplicationId = "Chave"
            };

            request.Query = txtEndereco.Text;
 
            // Make asynchronous call to fetch the geo coordinate data.
            _svc.GeocodeAsync(request);
        }

    }
}