using C1.Xaml.Maps;
using System;
using System.Collections.Generic;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;

namespace ControlExplorer.Controls.Maps
{
    public partial class CustomTiles
        : UserControl
    {
        public CustomTiles()
        {
            InitializeComponent();

            MapsHelper.CheckConnection();

            maps.Source = null;
            Loaded += CustomTiles_Loaded;
        }

        void CustomTiles_Loaded(object sender, RoutedEventArgs e)
        {
            maps.Source = new OpenStreetMapsSource();
        }
    }


    public class OpenStreetMapsSource : C1MultiScaleTileSource
    {
        private readonly string[] tilePathPrefixes = new[] { "a", "b", "c" };
        private readonly Random rand = new Random();
        private const string uriFormat = @"http://{S}.tile.openstreetmap.org/{Z}/{X}/{Y}.png";

        public OpenStreetMapsSource()
            : base(0x8000000, 0x8000000, 0x100, 0x100, 0)
        { }

        protected override void GetTileLayers(int tileLevel, int tilePositionX, int tilePositionY, IList<object> sources)
        {
            if (tileLevel > 8)
            {
                var zoom = tileLevel - 8;
                var prefix = tilePathPrefixes[rand.Next(3)];
                var url = uriFormat;

                url = url.Replace("{S}", prefix);
                url = url.Replace("{Z}", zoom.ToString());
                url = url.Replace("{X}", tilePositionX.ToString());
                url = url.Replace("{Y}", tilePositionY.ToString());
                sources.Add(new Uri(url));
            }
        }
    }
}