﻿using System;
using System.Collections.Generic;
using System.Linq;

using OpenQA.Selenium;

using BoxMe.ConsoleControls;

using DEFAULT = BoxMe.ConsoleControls.DefaultControl;
using HTML = BoxMe.ConsoleControls.HtmlControl;
using HEAD = BoxMe.ConsoleControls.HeadControl;
using TITLE = BoxMe.ConsoleControls.TitleControl;
using BODY = BoxMe.ConsoleControls.BodyControl;
using HEADING = BoxMe.ConsoleControls.HeadingControl;


namespace BoxMe.ConsoleControls
{
	public class Browser
	{
		readonly IConsole _Console;
		
		internal Browser(IConsole console)
		{
			_Console = console;		
		}
		
		public void Load(IWebDriver driver, string url)
		{
			driver.Navigate().GoToUrl(url);
			var webElement = driver.FindElement(by: By.TagName("html"));
			var boxMeDom = webElement.GetTagElements();
				
			boxMeDom.Render(_Console);
		}
		
		//-------------------------------------------------
		internal string GetScreenshot()
		{
			return _Console.GetScreenshot();
		}
		internal string GetTitle()
		{
			return _Console.Title;
		}
		//-------------------------------------------------
			
	}
	static class BrowserExtentions
	{
		/// <remarks>
		/// I am hoping for something more elegant soon
		/// </remarks>
		public static ITagElement GetTagElements(this IWebElement source)
		{			
			ITagElement result = null;	

			switch (source.TagName) {
				case "html":
					result = new TagElement<HTML>(new HTML());
					break;
				case "head":
					result = new TagElement<HEAD>(new HEAD());
					break;
				case "title":
					result = new TagElement<TITLE>(new TITLE(source.Text));
					break;
				case "body":
					result = new TagElement<BODY>(new BODY());
					break;
				case "h1":
					result = new TagElement<HEADING>(new HEADING(HeadingLevel.H1, source.Text));
					break;
				default:
					return new TagElement<DEFAULT>(new DEFAULT(source.Text));
			}			
			
			var children = source.FindElements(By.XPath("*"));
			var query = 
				from thing in children
				select (thing).GetTagElements();
			
			result.ChildrenNodes.AddRange(query);
			return result;
			
		}
	}
}
