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.Maps.MapControl;


namespace TileOverlay
{
    public partial class MainPage : UserControl
    {
        MapTileLayer tileLayer;
        private double tileOpacity = 1.0;

        public MainPage()
        {
            InitializeComponent();
        }

        private void AddTerrainTileOverlay()
        {
            // The bounding rectangle that the tile overlay can be placed within.
            LocationRect boundingRect = new LocationRect(
                new Location(48.06282, -122.43773),
                new Location(47.999973, -122.37490));

            // Creates a new map layer to add the tile overlay to.
            tileLayer = new MapTileLayer();

            // The source of the overlay.
            LocationRectTileSource tileSource = new LocationRectTileSource();
            tileSource.UriFormat = "http://www.microsoft.com/virtualearth/isdk/ajax/layers/lidar/{quadkey}.png";
            // The zoom range that the tile overlay is visibile within
            tileSource.ZoomRange = new Range<double>(10, 18);
            // The bounding rectangle area that the tile overaly is valid in.
            tileSource.BoundingRectangle = boundingRect;


            // Adds the tile overlay to the map layer
            tileLayer.TileSources.Add(tileSource);

            // Adds the map layer to the map
            if (!MapTileOverlay.Children.Contains(tileLayer))
            {
                MapTileOverlay.Children.Add(tileLayer);
            }
            tileLayer.Opacity = tileOpacity;
        }

        private void btnAddTileLayer_Click(object sender, RoutedEventArgs e)
        {
            // Adds the tile overlay on the map, if it doesn't already exist.
            if (tileLayer != null)
            {
                if (!MapTileOverlay.Children.Contains(tileLayer))
                {
                    MapTileOverlay.Children.Add(tileLayer);
                }
            }
            else
            {
                AddTerrainTileOverlay();
            }
        }

        private void btnRemoveTileLayer_Click(object sender, RoutedEventArgs e)
        {
            // Removes the tile overlay if it has been added to the map.
            if (MapTileOverlay.Children.Contains(tileLayer))
            {
                MapTileOverlay.Children.Remove(tileLayer);
            }
        }

    }
}
