using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using OpenQA.Selenium;              // contains: IWebDriver
using OpenQA.Selenium.Support.UI;   // contains: WebDriverWait, ExpectedConditions [requires Selenium.Support package]
using OpenQA.Selenium.Firefox;      // contains: FirefoxDriver
using System.Threading;
using OpenQA.Selenium.Chrome;

namespace SeleniumTests
{
 [TestClass]
 public class AnmeldedialogTest
 {

  public IWebDriver GetDriver()
  {
   string driver = System.Configuration.ConfigurationManager.AppSettings["DRIVER"].ToString();
   switch (driver)
   {
    case "Chrome":    return new ChromeDriver();
    case "Firefox": return new FirefoxDriver();
   }
   return new ChromeDriver();
  }

  [TestMethod]
  public void AnmeldenTest()
  {
   var anmeldename = "testuser";
   var kennwort = "geheim";

   string url = System.Configuration.ConfigurationManager.AppSettings["URL"].ToString();
   Console.WriteLine("Teste URL " + url);

   using (IWebDriver b = GetDriver())
   {
    //b.Manage().Timeouts().PageLoad = TimeSpan.FromSeconds(5);
    //b.Manage().Window.Maximize();

    b.Navigate().GoToUrl(url);

    IWebElement cmdSearch = b.FindElement(By.CssSelector("start h2"));
    Assert.AreEqual(cmdSearch.Text, "Benutzeranmeldung");

    b.FindElement(By.Id("name")).SendKeys(anmeldename);
    b.FindElement(By.Id("password")).SendKeys(kennwort);
    b.FindElement(By.Id("Anmelden")).Click();

    ((ITakesScreenshot)b).GetScreenshot().SaveAsFile(@"Screenshot1.png", ScreenshotImageFormat.Png);

    //Thread.Sleep(1000); :-(

    WebDriverWait wait = new WebDriverWait(b, TimeSpan.FromSeconds(5));
    wait.Until(d => b.Url.EndsWith("/app"));

    Assert.IsTrue(b.Url.EndsWith("/app"));

    ((ITakesScreenshot)b).GetScreenshot().SaveAsFile(@"Screenshot2.png", ScreenshotImageFormat.Png);

    Assert.AreEqual(b.FindElement(By.Id("LoggedInUser")).Text, "Current User: " + anmeldename);

     //// Wait for results to show
    //WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(10));
    //wait.Until(d => ExpectedConditions.ElementIsVisible(By.Id("resultStats")));

    //// Extract results from webpage and print to log file
    //IWebElement lbl_Results = driver.FindElement(By.Id("resultStats"));
    //Console.WriteLine("Results: " + lbl_Results.Text);

    b.Quit();
   }
  }
 }
}