using System;
using Selenium;
using NUnit.Framework;
using Orciid.Core;
using System.IO;

namespace webtests
{
	public class SeleniumTestFixture
	{
		protected ISelenium selenium;
        
		protected virtual void MoreSetUp()
		{
		}

		protected virtual void MoreTearDown()
		{
		}
	
		private static string baseurl = null;

		[SetUp]
		public void SetUp() 
		{
			Utilities util = new Utilities(Directory.GetCurrentDirectory());

			string server;
			int port;
			string browser;

			try
			{
				server = Configuration.Instance.GetString("selenium.server");
				port = Int32.Parse(Configuration.Instance.GetString("selenium.port"));
				browser = Configuration.Instance.GetString("selenium.browser");
				baseurl = Configuration.Instance.GetString("selenium.baseurl");
			}
			catch (Exception ex)
			{
				throw new ApplicationException("Failed to read Selenium configuration", ex);
			}

			selenium = new DefaultSelenium(server, port, browser, baseurl);
			selenium.Start();
			MoreSetUp();
		}
                
		[TearDown]
		public void TearDown() 
		{
			MoreTearDown();
			selenium.Stop();
		}

		internal static void LoginAdministrator(ISelenium selenium)
		{
			Assert.IsNotNull(baseurl);
			Assert.IsTrue(baseurl.Length > 0);
			Assert.AreEqual('/', baseurl[baseurl.Length - 1]);
			selenium.Open(baseurl + "default.aspx");
			if (selenium.IsTextPresent("LOG OUT"))
			{
				selenium.Click("link=LOG OUT");
				selenium.WaitForPageToLoad("30000");
			}
			Assert.IsTrue(selenium.IsTextPresent("Welcome"));
			Assert.IsTrue(selenium.IsTextPresent("User name:"));
			Assert.IsTrue(selenium.IsTextPresent("Password:"));
			selenium.Type("UsernameTextBox", "admin");
			selenium.Type("PasswordTextBox", "admin");
			selenium.Click("LoginButton");
			selenium.WaitForPageToLoad("30000");
			if (selenium.IsTextPresent("Browser Compatibility Check"))
				selenium.WaitForPageToLoad("30000");
			Assert.IsTrue(selenium.IsTextPresent("Announcements"));
		}
	}
}
