package com.dkallus.adptimesaver.automation.page.home;

import java.util.Date;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;

import com.dkallus.adptimesaver.automation.util.DateUtils;

public class Entry {
	private final WebDriver driver;

	private int index;
	private Date date;

	public Entry(WebDriver driver, int index, Date date, boolean firstEntry) {
		this.driver = driver;
		this.index = index;
		this.date = date;

		if (!firstEntry) {
			createNewEntry();
		} else {
			createFirstEntry();
		}
	}

	private void createFirstEntry() {
		WebElement addNewEntry = driver.findElement(By.id("AddNewEntry"));
		addNewEntry.click();
	}

	private void createNewEntry() {
		WebElement addNewEntry = driver.findElement(By
				.xpath("//*[@id=\"TimeEntriesRepeater." + (index - 1)
						+ "\"]/td[1]/p/a[1]"));
		addNewEntry.click();
	}

	public Date getDate() {
		if (date == null) {
			WebElement dateText = driver.findElement(By
					.id("TimeEntriesRepeater." + index + ".FRMEntryDate"));

			date = DateUtils.parseDate(dateText.getAttribute("value"));
		}

		return date;
	}

	public void setDate(Date newDate) {
		date = newDate;
	}

	public void typeDate(Date newDate) {
		date = newDate;

		WebElement dateText = driver.findElement(By.id("TimeEntriesRepeater."
				+ index + ".FRMEntryDate"));

		dateText.clear();
		dateText.sendKeys(DateUtils.formatDate(date));
	}

	public void typeStartTime(String time) {
		WebElement end = driver.findElement(By.id("TimeEntriesRepeater."
				+ index + ".FRMStartTime"));

		end.sendKeys(time);
	}

	public void typeEndTime(String time) {
		WebElement start = driver.findElement(By.id("TimeEntriesRepeater."
				+ index + ".FRMEndTime"));

		start.sendKeys(time);
	}

	public void save() {
		WebElement saveEntry = driver.findElement(By
				.xpath("//*[@id=\"TimeEntriesRepeater." + index
						+ "\"]/td[1]/p/a[1]"));
		saveEntry.click();
	}

}
