﻿using System;
using System.Linq;
using OKHOSTING.UI;
using OKHOSTING.ORM;
using OKHOSTING.ORM.Operations;
using OKHOSTING.Broadcasting;
using OKHOSTING.Broadcasting.Web;

namespace OKHOSTING.UDG.TV
{
	public class IndexController : Controller
	{
		public IndexController(IPage page) : base(page)
		{
		}

		protected override void OnStart()
		{
			var types = new Type[]
			{
				typeof(WeeklySchedule),
				typeof(Medium),
				typeof(Transmission),
				typeof(Show),
				typeof(Content),
				typeof(Episode),

				typeof(StreamingChannel),
				typeof(PodcastChannel),
				typeof(PodcastTransmission),

				typeof(UserFeedback),
				typeof(UserComment),
				typeof(UserRating),
				typeof(UserConnection),

				//typeof(Logs.Log),
			};

			Core.BaitAndSwitch.PlatformSpecificConstructors.Add(typeof(DataBase), DataBase_Setup);
			var dtypes = DataType.CreateDataTypes(types).ToArray();

			//convert timespan to ticks
			DataMember.SetConverter(new ORM.Conversions.TimeSpanConverter(), typeof(TimeSpan));
			DataMember.SetConverter(new ORM.Conversions.UriConverter(), typeof(Uri));

			Finish();

			new SplashScreenController(Page).Start();
		}

		private static DataBase DataBase_Setup()
		{
            var db = new DataBase(new SQL.WebService.Client.JsonClient() { ConnectionString = "http://api.udgtv.com/JsonWebService/" }, new SQL.DbProviders.MySql.SQLGenerator());
			db.BeforeOperation += Db_BeforeOperation;

			return db;
		}

		private static void Db_BeforeOperation(DataBase sender, OperationEventArgs eventArgs)
		{
			if (eventArgs.Operation is Insert && eventArgs.Operation.DataType.PrimaryKey.Count() == 1 && eventArgs.Operation.DataType.PrimaryKey.Single().Expression.ReturnType.Equals(typeof(Guid)))
			{
				var pk = eventArgs.Operation.DataType.PrimaryKey.Single();
				object instance = ((Insert)eventArgs.Operation).Instance;
				var pkValue = (Guid)pk.Expression.GetValue(instance);

				//create new Guid before insert, if current value is empty
				if (pkValue == null || pkValue.Equals(Guid.Empty))
				{
					pk.SetValueFromColumn(instance, Guid.NewGuid());
				}
			}
		}
	}
}