using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Maps.MapControl;
using Microsoft.Maps.MapControl.Core;

namespace SLCommon.TileLayers.Custom
{
    public class CityTileLayer : LocationRectTileSource
    {
        public CityTileLayer()
        {
            // Define the Bounding Rectangle
            //Note: setting north and south to 90 and -90 results in an error in the control, no tiles will be loaded.
            //using 85 and -85 is exceptable.
            LocationRect boundingRect = new LocationRect(85, -180, -85, 180);

            string strFullUrl = System.Windows.Application.Current.Host.Source.AbsoluteUri;

            if (strFullUrl.IndexOf("/ClientBin") > 0)
            {
                strFullUrl = strFullUrl.Substring(0, strFullUrl.IndexOf("/ClientBin")) + "/Handlers/TileRendererHandler.ashx?quadkey={0}";
            }

            // Set the Uri for the custom Map Imagery Tiles
            UriFormat = strFullUrl;

            // Set the Min and Max Zoom Levels that the imagery is to be visible within
            ZoomRange = new Range<double>(1, 19);

            // The bounding rectangle area that the tile overaly is valid in.
            BoundingRectangle = boundingRect;
        }

        public override Uri GetUri(int x, int y, int zoomLevel)
        {
            var quadKey = new QuadKey(x, y, zoomLevel);
            var uri = new Uri(String.Format(this.UriFormat, quadKey.Key), UriKind.RelativeOrAbsolute);
            return uri;
        } 
    }
}
