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 C1.Silverlight.Maps;

namespace MapsSamples
{
    public partial class CustomTileSource : UserControl
    {
        public CustomTileSource()
        {
            InitializeComponent();

            this.Loaded += CustomTileSource_Loaded;
        }

        void CustomTileSource_Loaded(object sender, RoutedEventArgs e)
        {
            OSMSource.Source = new OpenStreetMapsSource();
            OSMSource.Zoom = 1.0;
        }
    }

    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));
            }
        }
    }
}
