using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using C1.Web.Wijmo.Controls.C1Maps;
using System.Collections.ObjectModel;
using System.Drawing;
using System.IO;
namespace ControlExplorer.C1Maps
{
	public class City
	{
		public string Name { get; set; }
		public PointD GeoPoint { get; set; }
		public string Country { get; set; }
		public int Population { get; set; }

		public override string ToString()
		{
			return string.Format("{0}\t{1}\t{2}\t{3}", Name, GeoPoint, Population, Country);
		}

		public static City FromString(string s)
		{
			City city = null;
			if (!string.IsNullOrEmpty(s))
			{
				string[] ss = s.Split('\t');
				if (ss.Length == 4)
				{
					city = new City()
					{
						Name = ss[0],
						GeoPoint = PointFromString(ss[1]),
						Population = int.Parse(ss[2]),
						Country = ss[3]
					};
				}
			}

			return city;
		}

		static PointD PointFromString(string s)
		{
			string[] ss = s.Split(',');
			return new PointD(double.Parse(ss[1]), double.Parse(ss[0]));
		}

		public static List<City> Read(Stream stream)
		{
			List<City> cities = new List<City>();

			using (StreamReader sr = new StreamReader(stream))
			{
				for (; !sr.EndOfStream; )
				{
					City city = FromString(sr.ReadLine());
					if (city != null)
						cities.Add(city);
				}
			}

			return cities;
		}
	}

	public partial class Cities : System.Web.UI.Page
	{
		protected void Page_Load(object sender, EventArgs e)
		{
			if (!IsPostBack)
			{
				var layer = new C1VectorLayer();
				C1Maps1.Layers.Add(layer);

				layer.Placemark.LabelVisibility = LabelVisibility.AutoHide;
				layer.DataType = DataType.WijJson;

				var citiesData = new WijJsonData();
				layer.DataWijJson = citiesData;

				using (System.IO.FileStream stream = new FileStream(Server.MapPath("Resources/Cities100K.txt"), FileMode.Open, FileAccess.Read))
				{
					var cities = City.Read(stream);
					foreach (var city in cities)
					{
						var placemark = new C1VectorPlacemark();
						placemark.Name = city.Name;
						placemark.Point = city.GeoPoint;
						placemark.Lod = GetLod(city);
						citiesData.Vectors.Add(placemark);
					}
				}
			}
		}

		private LOD GetLod(City city) {
			if (city.Population >= 2000000)
				return new LOD(0, 0, 1, 20);

			if (city.Population >= 1000000)
				return new LOD(0, 0, 2, 20);

			if (city.Population >= 7500000)
				return new LOD(0, 0, 3, 20);

			if (city.Population >= 500000)
				return new LOD(0, 0, 4, 20);

			if (city.Population >= 250000)
				return new LOD(0, 0, 5, 20);

			return new LOD(0, 0, 6, 20);
		}
	}
}