package Requisition;

import java.io.IOException;
import java.time.Duration;
import java.time.LocalDate;
import java.util.Calendar;
import java.util.Iterator;
import java.util.List;
import java.util.Random;

import org.apache.poi.ss.usermodel.Sheet;
import org.openqa.selenium.By;
import org.openqa.selenium.Keys;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.interactions.Actions;
import org.openqa.selenium.support.PageFactory;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;

import RevalERP_HRMS.basesetup.BaseSetup;
import RevalERP_HRMS.elements.Requisition_Elements;
import RevalERP_HRMS.excels.Excels;
import RevalERP_HRMS.utils.CommonUtils;

public class Requisition_Creation extends BaseSetup {

	public Sheet sheet;
	public Requisition_Elements Elements;
	public WebDriverWait wait;
	public int attempts = 0;
	public int maxAttempts = 3;
	public int i;

	@BeforeClass
	public void setUp() throws Throwable {
		// openbrowser();
		CommonUtils.ModuleName = "Requisition_Creation";
		driver = getDriver();
		driver.manage().window().maximize();
		driver.get(baseUrl);
		CommonUtils.Reports("Requisition_Creation.html", "Requisition_Creation");
		sheet = CommonUtils.readExcellSheet(Excels.filepath + "Requisition_TestData.xls", 0);
		Elements = PageFactory.initElements(driver, Requisition_Elements.class);
		CommonUtils.login();
		wait = new WebDriverWait(driver, Duration.ofSeconds(20));
	}

	@Test(priority = 1)
	public void NavigateAddRequisitionPage_Tc_01() throws IOException {
		driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(10)); // while(attempts<maxAttempts) {
		try {

			try {
				if (Elements.HRMS.isDisplayed()) {
					CommonUtils.scrollTOElement(Elements.HRMS, driver);
					CommonUtils.Thread_Sleep(2);
					CommonUtils.JS_Click(driver, Elements.HRMS);
					CommonUtils.captureScreenshot_pass(driver, "TC_001",
							"Home page Hrms Main modules is visable and clickable also");
				}
			} catch (Exception E) {
				CommonUtils.captureScreenshot_fail(driver, "TC_001",
						"Home page Hrms Main modules is  not visable and unable clickable also");

			}
			CommonUtils.Thread_Sleep(2);
			try {
				if (Elements.Requisition.isDisplayed()) {
					CommonUtils.scroll_down(driver);
					CommonUtils.JS_Click(driver, Elements.Requisition);
					CommonUtils.captureScreenshot_pass(driver, "TC_002",
							"Inside the  HRMS -Requisition section is displayed and click able alos");
				}
			} catch (Exception E) {
				CommonUtils.captureScreenshot_fail(driver, "TC_002",
						"Inside the  HRMS -Requisition section is  not displayed and unable to click able alos");

			}
			CommonUtils.Thread_Sleep(3);
			wait.until(ExpectedConditions.visibilityOf(Elements.Requisition_Module));
			CommonUtils.JS_Click(driver, Elements.Requisition_Module);
			CommonUtils.Thread_Sleep(3);
			wait.until(ExpectedConditions.visibilityOf(Elements.AddRequisition_Button));
			CommonUtils.JS_Click(driver, Elements.AddRequisition_Button);
			// break;
		} catch (Exception e2) {

			// attempts++;
			// if (attempts==maxAttempts) {
			// throw e2;
		}
		// }
	}

	@Test(priority = 2)
	public void test() throws IOException, InterruptedException {
		for (int k = 0; k < sheet.getLastRowNum(); k++) {
			System.out.println("total rows " + sheet.getLastRowNum());
			i = k;
			General_TextField();
			CommonUtils.scroll_up(driver);
			General_Dropdowns();
			General_Datapicker();
			General_ChoosesileField();
			MultiSelectDropdown();
			General_TextArea();
			CommonUtils.scroll_down(driver);
			CommonUtils.scroll_down(driver);
			Thread.sleep(2000);
			saveAsDraft();
			Thread.sleep(2000);
			sendForApproval();
			
			// driver.navigate().refresh();
		}
	}

	public void saveAsDraft() throws IOException, InterruptedException {

		WebElement saveAsDraftButton = driver.findElement(By.xpath("//*[text()='Save As Draft']"));
		saveAsDraftButton.click();
		try {
			CommonUtils.captureScreenshot_pass(driver, "TC-0" + "SaveAsDraft" + "1",
					"TC-0" + "SaveAsDraft" + " 1-clicked on " + "SaveAsDraft" + " button field ");
			System.out.println("TC-0" + "SaveAsDraft" + "failed");

		} catch (Exception e) {

			CommonUtils.captureScreenshot_fail(driver, "TC-0" + "SaveAsDraft" + "1",
					"TC-0" + "SaveAsDraft" + " 1-clicked data in " + "SaveAsDraft" + " button field ");
			System.out.println("TC-0" + "SaveAsDraft" + "passed");
		}
		Thread.sleep(2000);
	}

	public void sendForApproval() throws IOException, InterruptedException {
		WebElement sendForApprovalButton = driver.findElement(By.xpath("//*[text()='Send for Approval']"));
		sendForApprovalButton.click();
		try {
			CommonUtils.captureScreenshot_pass(driver, "TC-0" + "sendForApproval" + "1",
					"TC-0" + "sendForApproval" + " 1-clicked on " + "sendForApproval" + " button field ");
			System.out.println("TC-0" + "sendForApproval" + "failed");
		} catch (Exception e) {

			CommonUtils.captureScreenshot_fail(driver, "TC-0" + "sendForApproval" + "1",
					"TC-0" + "sendForApproval" + " 1-clicked data in " + "sendForApproval" + " button field ");
			System.out.println("TC-0" + "sendForApproval" + "passed");
		}
		Thread.sleep(2000);
		WebElement continuelButton = driver.findElement(By.xpath("//*[text()='Send for Approval']"));
		continuelButton.click();
		try {
			CommonUtils.captureScreenshot_pass(driver, "TC-0" + "continuelButton" + "1",
					"TC-0" + "continuelButton" + " 1-clicked on " + "continuelButton" + " button field ");
			System.out.println("TC-0" + "continuelButton" + "failed");
		} catch (Exception e) {

			CommonUtils.captureScreenshot_fail(driver, "TC-0" + "continuelButton" + "1",
					"TC-0" + "continuelButton" + " 1-clicked data in " + "continuelButton" + " button field ");
			System.out.println("TC-0" + "continuelButton" + "passed");
		}

		try {
			WebElement successMessage = driver.findElement(By.xpath("//*[@class=' notifyDiv ng-star-inserted']"));
			if (successMessage.isDisplayed()) {
			CommonUtils.captureScreenshot_pass(driver, "TC-0" + "continuelButton" + "1",
					"TC-0" + "continuelButton" + " 1-clicked on " + "continuelButton" + " button field ");
			System.out.println("TC-0" + "continuelButton" + "failed");
			}
		} catch (Exception e) {

			CommonUtils.captureScreenshot_fail(driver, "TC-0" + "continuelButton" + "1",
					"TC-0" + "continuelButton" + " 1-clicked data in " + "continuelButton" + " button field ");
			System.out.println("TC-0" + "continuelButton" + "passed");
		}
	}

	public void General_TextField() throws IOException {
		// CommonUtils.implicit_Wait(10);
		List<WebElement> textfieldlabels = driver.findElements(By.xpath(
				"//div[contains(@class,'form-line-Item')]//label[@for=//input[(@type='text' or @type='number')      and not(@data-uid)      and not(contains(@class,'datepicker'))      and not(@readonly='true')]/@id]"));
		for (int cell = 1; cell <= sheet.getRow(i).getLastCellNum(); cell++) {
			String header = CommonUtils.getExcellData(0, cell, sheet);
			System.out.println("Header Name: " + header);
			for (int m = 1; m <= textfieldlabels.size(); m++) {
				System.out.println("TextFieldLabel Size : " + textfieldlabels.size());
				WebElement textfieldlabel = driver.findElement(By.xpath(
						"(//div[contains(@class,'form-line-Item')]//label[@for=//input[(@type='text' or @type='number')      and not(@data-uid)      and not(contains(@class,'datepicker'))      and not(@readonly='true')]/@id])"
								+ "[" + m + "]"));
				String label = textfieldlabel.getText();
				System.out.println("Label Name : " + label);
				WebElement textfield = driver.findElement(By.xpath(
						"(//div[contains(@class,'form-line-Item')]//input[(@type='text' or @type='number') and not(@data-uid) and not(contains(@class,'datepicker')) and not(@readonly='true') and not(contains(@aria-label,'multiselect-search'))])"
								+ "[" + m + "]"));

				// if (label.equalsIgnoreCase(header)) {
				if (label.contains(header)) {
					CommonUtils.JS_Click(driver, textfield);
					if (label.equals(CommonUtils.getExcellData(0, cell, sheet))) { // Validating whether it is Device
																					// Number field or not`
						textfield.sendKeys(CommonUtils.getExcellData(i + 1, cell, sheet));
						System.out.println("Data from Excel : " + CommonUtils.getExcellData(i + 1, cell, sheet));
						// CommonUtils.Thread_Sleep(1);
					} else {
						textfield.sendKeys(CommonUtils.getExcellData(i + 1, cell, sheet));
					}
					try {
						if (Elements.Invalid_textfield.isDisplayed()) {
							CommonUtils.captureScreenshot_fail(driver, "TC-0" + m + "1",
									"TC-0" + m + " 1-enter valid data in " + header + " text field ");
							System.out.println("TC-0" + m + "failed");
						}
					} catch (Exception e) {

						CommonUtils.captureScreenshot_pass(driver, "TC-0" + m + "1",
								"TC-0" + m + " 1-enter valid data in " + header + " text field ");
						System.out.println("TC-0" + m + "passed");
					}

				}

			}
		}
	}

	public void MultiSelectDropdown() throws IOException {// Multi select drop down
		// CommonUtils.implicit_Wait(10);
		List<WebElement> textfieldlabels = driver.findElements(By.xpath("//*[@id='HRMSTechnologyId']/div/div[1]/span"));
		for (int cell = 1; cell <= sheet.getRow(i).getLastCellNum(); cell++) {
			String header = CommonUtils.getExcellData(0, cell, sheet);
			System.out.println("Header Name: " + header);
			for (int m = 1; m <= textfieldlabels.size(); m++) {
				System.out.println("TextFieldLabel Size : " + textfieldlabels.size());
				WebElement textfieldlabel = driver
						.findElement(By.xpath("(//label[@for='HRMSTechnologyId'])" + "[" + m + "]"));
				String label = textfieldlabel.getText();
				System.out.println("Label Name : " + label);
				WebElement textfield = driver
						.findElement(By.xpath("(//*[@id='HRMSTechnologyId']/div/div[1]/span)" + "[" + m + "]"));

				// if (label.equalsIgnoreCase(header)) {
				if (label.contains(header)) {
					CommonUtils.JS_Click(driver, textfield);
					if (label.equals(CommonUtils.getExcellData(0, cell, sheet))) { // Validating whether it is Device
																					// Number field or not`
						// MultiDropdown Search Box
						WebElement searchTextfield = driver
								.findElement(By.xpath("//li[@class='filter-textbox']/input"));
						searchTextfield.sendKeys(CommonUtils.getExcellData(i + 1, cell, sheet));
						System.out.println("Data from Excel : " + CommonUtils.getExcellData(i + 1, cell, sheet));
						CommonUtils.Thread_Sleep(2);
						List<WebElement> listOfSkills = driver.findElements(
								By.xpath("(//li[@class='multiselect-item-checkbox']//div)[" + i + 1 + "]"));
						for (int i = 0; i < listOfSkills.size(); i++) {
							WebElement skillCheckbox = listOfSkills.get(i);
							skillCheckbox.click();
						}
					} else {
						System.out.println("Header not matched");
					}
					try {
						if (Elements.Invalid_textfield.isDisplayed()) {
							CommonUtils.captureScreenshot_fail(driver, "TC-0" + m + "1",
									"TC-0" + m + " 1-enter valid data in " + header + " text field ");
							System.out.println("TC-0" + m + "failed");
						}
					} catch (Exception e) {

						CommonUtils.captureScreenshot_pass(driver, "TC-0" + m + "1",
								"TC-0" + m + " 1-enter valid data in " + header + " text field ");
						System.out.println("TC-0" + m + "passed");
					}

				}

			}
		}
	}

	public void General_TextArea() throws IOException { // Text area
		// CommonUtils.implicit_Wait(10);
		List<WebElement> textfieldlabels = driver.findElements(By.xpath(
				"//div[contains(@class,'form-line-Item')]//label[     not(@for=//input[(@type='text' or @type='number')]/@id)      and not(@data-uid)      and not(contains(@class,'datepicker'))      and not(@readonly='true')      and not(contains(@aria-label,'multiselect-search'))     and not(contains(@for,'dropdown'))  and not(contains(@for,'HRMSTechnologyId')) and not(contains(@for,'formFile')) and not(contains(@for,'textareaReviewerComments'))]"));
		for (int cell = 1; cell <= sheet.getRow(i).getLastCellNum(); cell++) {
			String header = CommonUtils.getExcellData(0, cell, sheet);
			System.out.println("Header Name: " + header);
			for (int m = 1; m <= textfieldlabels.size(); m++) {
				System.out.println("TextFieldLabel Size : " + textfieldlabels.size());
				WebElement textfieldlabel = driver.findElement(By.xpath(
						"(//div[contains(@class,'form-line-Item')]//label[     not(@for=//input[(@type='text' or @type='number')]/@id)      and not(@data-uid)      and not(contains(@class,'datepicker'))      and not(@readonly='true')      and not(contains(@aria-label,'multiselect-search'))     and not(contains(@for,'dropdown'))  and not(contains(@for,'HRMSTechnologyId')) and not(contains(@for,'formFile')) ])"
								+ "[" + m + "]"));
				String label = textfieldlabel.getText();
				System.out.println("Label Name : " + label);
				WebElement textfield = driver
						.findElement(By.xpath("(//div[@class='inputWithTooltip']/textarea)" + "[" + m + "]"));

				// if (label.equalsIgnoreCase(header)) {
				if (label.contains(header)) {
					CommonUtils.JS_Click(driver, textfield);
					if (label.equals(CommonUtils.getExcellData(0, cell, sheet))) { // Validating whether it is Device
																					// Number field or not`
						textfield.sendKeys(CommonUtils.getExcellData(i + 1, cell, sheet));
						System.out.println("Data from Excel : " + CommonUtils.getExcellData(i + 1, cell, sheet));
						// CommonUtils.Thread_Sleep(1);
					} else {
						textfield.sendKeys(CommonUtils.getExcellData(i + 1, cell, sheet));
					}
					try {
						if (Elements.Invalid_textfield.isDisplayed()) {
							CommonUtils.captureScreenshot_fail(driver, "TC-0" + m + "1",
									"TC-0" + m + " 1-enter valid data in " + header + " text field ");
							System.out.println("TC-0" + m + "failed");
						}
					} catch (Exception e) {

						CommonUtils.captureScreenshot_pass(driver, "TC-0" + m + "1",
								"TC-0" + m + " 1-enter valid data in " + header + " text field ");
						System.out.println("TC-0" + m + "passed");
					}

				}

			}
		}
	}
	
	
	public void General_ChoosesileField() throws IOException {
		// CommonUtils.implicit_Wait(10);
		List<WebElement> uploadfieldlabels = driver
				.findElements(By.xpath("(//*[contains(@class, 'form-line-Item')])//*[@for='formFile']"));
		for (int cell = 1; cell <= sheet.getRow(i).getLastCellNum(); cell++) {
			String header = CommonUtils.getExcellData(0, cell, sheet);
			for (int m = 1; m <= uploadfieldlabels.size(); m++) {
				WebElement uploadfieldlabel = driver.findElement(
						By.xpath("((//*[contains(@class, 'form-line-Item')])//*[@for='formFile'])[" + m + "]"));
				String label = uploadfieldlabel.getText();
				WebElement uploadfield = driver.findElement(By.xpath(
						"((//*[contains(@class, 'form-line-Item')])//*[@for='formFile']/../div/div/input)[" + m + "]"));

				if (label.equalsIgnoreCase(header)) {
					CommonUtils.JS_Click(driver, uploadfield);
					uploadfield.sendKeys(Excels.filepath7 + "JobDescriptionDeveloper.docx");
					// CommonUtils.Thread_Sleep(1);
					try {
						if (Elements.Invalid_textfield.isDisplayed()) {
							CommonUtils.captureScreenshot_fail(driver, "TC-0" + m + "1",
									"TC-0" + m + " 1-enter valid data in " + header + " text field ");
							System.out.println("TC-0" + m + "failed");
						}
					} catch (Exception e) {

						CommonUtils.captureScreenshot_pass(driver, "TC-0" + m + "1",
								"TC-0" + m + " 1-enter valid data in " + header + " text field ");
						System.out.println("TC-0" + m + "passed");
					}

				}

			}
		}
	}

	public void General_Dropdowns() throws IOException {
		// CommonUtils.implicit_Wait(10);
		List<WebElement> dropdwonlabels = driver.findElements(By.xpath("//*[@role='combobox']/../../../../../label"));
		for (int cell = 1; cell < sheet.getRow(i).getLastCellNum(); cell++) {
			String header = CommonUtils.getExcellData(0, cell, sheet);
			System.out.println("Header Name: " + CommonUtils.getExcellData(0, cell, sheet));
			for (int m1 = 1; m1 <= dropdwonlabels.size(); m1++) {
				System.out.println(dropdwonlabels.size());
				WebElement dropdownlabel = driver
						.findElement(By.xpath("(//*[@role='combobox']/../../../../../label)[" + m1 + "]"));
				String label = dropdownlabel.getText();
				WebElement dropdown = driver.findElement(
						By.xpath("(//*[@role='combobox']/../../../../../label)[" + m1 + "]/..//div[@*='listbox']"));
				if (label.equalsIgnoreCase(header)) {
					CommonUtils.JS_Click(dropdown);
					if (label.equals(CommonUtils.getExcellData(0, cell, sheet))) {
						WebElement value = driver.findElement(By.xpath("(//*[@role='combobox'])[" + m1 + "]/input"));
						value.sendKeys(CommonUtils.getExcellData(i + 1, cell, sheet) + Keys.ENTER);
						// CommonUtils.Thread_Sleep(1);
					} else {
						WebElement value = driver.findElement(By.xpath("(//*[@role='combobox'])[" + m1 + "]/input"));
						value.sendKeys(CommonUtils.getExcellData(i + 1, cell, sheet) + Keys.ENTER);
					}

					try {
						if (Elements.NoItemFound.isDisplayed()) {
							CommonUtils.captureScreenshot_fail(driver, "TC-0" + m1 + "1",
									"TC-0" + m1 + " 2-enter valid data in " + header + " dropdown field ");
							System.out.println("TC-0" + m1 + "failed");
						}
					} catch (Exception e) {
						CommonUtils.captureScreenshot_pass(driver, "TC-0" + m1 + "1",
								"TC-0" + m1 + " 2-enter valid data in " + header + " dropdown field ");
						System.out.println("TC-0" + m1 + "passed");
					}
				}
			}
		}
	}


	public void General_Datapicker() throws IOException {
		// CommonUtils.implicit_Wait(10);
		List<WebElement> datapickerlabels = driver
				.findElements(By.xpath("//*[contains(@class, 'commonDate')]/div[1]/div/input/../../../label"));
		for (int cell = 1; cell < sheet.getRow(i).getLastCellNum(); cell++) {
			String header = CommonUtils.getExcellData(0, cell, sheet);
			for (int m = 1; m <= datapickerlabels.size(); m++) {
				WebElement datepickerlabel = driver.findElement(
						By.xpath("(//*[contains(@class, 'commonDate')]/div[1]/div/input/../../../label)[" + m + "]"));
				String label = datepickerlabel.getText();
				WebElement datepicker = driver
						.findElement(By.xpath("(//*[contains(@class, 'commonDate')]/div[1]/div/button)[" + m + "]"));
				if (label.equalsIgnoreCase(header)) {
					// Click the datepicker to open the calendar
					Actions act = new Actions(driver);
					act.click(datepicker).perform();
					CommonUtils.Thread_Sleep(2);


					// Get tomorrow's date
					Calendar calendar = Calendar.getInstance();
					calendar.add(Calendar.DATE, 1);
					int tomorrowDate = calendar.get(Calendar.DATE);
					System.out.println("tomorrowDate :" + tomorrowDate);
					// Select tomorrow's date
					WebElement date = driver.findElement(
							By.xpath("//td[not(contains(@class,'disabled'))]//span[text()='" + tomorrowDate + "']"));
					date.click();

					// if (dateFound) {
					try {
						if (Elements.Invalid_textfield.isDisplayed()) {
							CommonUtils.captureScreenshot_fail(driver, "TC-0" + m + "1",
									"TC-0" + m + " 3-enter valid date in " + header + " text field");
							System.out.println("TC-0" + m + " passed");
						}
					} catch (Exception e) {
						CommonUtils.captureScreenshot_pass(driver, "TC-0" + m + "1",
								"TC-0" + m + " 3-enter valid date in " + header + " text field");
						System.out.println("TC-0" + m + " failed");
					}
					// }
				}
			}
		}

	}
}
