using System;
using ATVO.ThemesSDK;
using ATVO.ThemeEditor.ThemeModels;
using ATVO.ThemeEditor.Scripting.DotNET;
using ATVO.ThemeEditor.Data;
using System.Collections.Generic;
using System.Linq;

namespace Scripts
{
	public class ChangeDriverInfoBottomBinding : IScript
	{
		public object Execute(ThemeContentItem item, object value, string parameter, ISimulation sim)
		{
			if (value is string)
			{
				var bindingKey = value?.ToString();
				Console.WriteLine("Changing driver info binding to " + bindingKey);

				var widgets = new List<Widget>();
				widgets.Add(item.Theme.Widgets.Find("W_DriverInfo"));
				widgets.Add(item.Theme.Widgets.Find("W_DriverInfoRight"));

				foreach (var widget in widgets)
				{			
					var binding = widget.DataSet.GetBindingByKey(bindingKey);		
					var subwidget = widget.SubWidgets.FirstOrDefault(sw => sw.Name.StartsWith("SW_DriverInfo"));
					var label = subwidget?.Labels.FirstOrDefault(l => l.Name.StartsWith("L_DriverInfoBottom"));
					if (label != null)
					{
						SetBinding(label, binding, bindingKey);
					}
					else 
					{
						Console.WriteLine("Did not find label");
					}					
				}
			}
			return null;
		}
		
		private void SetBinding(Label label, DataBindingBase binding, string key)
		{
			label.DataBindings.Clear();
			if (binding != null)
			{
				label.DataBindings.Add(binding);
				label.Text = GetTextFormat(key);
			}
			else
			{
				label.Text = "";
			}
		}

		private string GetTextFormat(string key)
		{
			switch (key)
			{
				case "fastlap":
					return "BEST LAP: {0}";
				case "prevlap":
					return "PREVIOUS LAP: {0}";
				case "curlap":
					return "CURRENT LAP: {0}";
				case "pitstoptime":
					return "PITSTOP: {0:0.0}";
				case "pitlanetime":
					return "PITLANE: {0:0.0}";
				case "pitstops":
					return "NUMBER OF STOPS: {0}";
				case "livespeed_kph":
					return "SPEED: {0:0} KM/H";
				case "livespeed_mph":
					return "SPEED: {0:0} MPH";
				case "classstartposition_ord":
					return "STARTED: {0}";
			}
			return "{0}";
		}
	}
}