package cz.moneta.test.dsl.hypos.pages.contract.loan;

import cz.moneta.test.dsl.hypos.pages.HyposPageFlow;
import cz.moneta.test.harness.context.StoreAccessor;
import cz.moneta.test.harness.endpoints.hypos.HyposEndpoint;
import cz.moneta.test.harness.support.web.*;
import org.openqa.selenium.WebElement;

import java.util.List;

import static cz.moneta.test.dsl.hypos.pages.contract.loan.DrawingConditionsApprovalPage.PAGE_TITLE;
import static cz.moneta.test.dsl.hypos.pages.contract.loan.DrawingConditionsApprovalPage.SAVE_BUTTON;

@Wait({PAGE_TITLE, SAVE_BUTTON})
public interface DrawingConditionsApprovalPage extends HyposPageFlow<DrawingConditionsApprovalPage>, StoreAccessor {
    String PAGE_TITLE = "//h1[contains(text(),'Odsouhlasení vybraných podmínek')]";
    String CONDITIONS_APPROVAL_TABLE = "//table[@id='terms-agreement-table']";
    String CONDITIONS_APPROVAL_ROW = CONDITIONS_APPROVAL_TABLE + "//tr[contains(@class,'tranche-row')]//input[contains(@class,'term-check') and not(@checked)]/../..";
    String CONDITIONS_APPROVAL_ROW_WITH_VALIDITY = CONDITIONS_APPROVAL_ROW + "//input[contains(@class,'term-unlimited-valid')]";

    String CONDITION_CHECK_CHECKBOX = "(" + CONDITIONS_APPROVAL_ROW + ")[%s]//input[contains(@class,'term-check')]";
    String CONDITION_VALIDITY_UNLIMITED_CHECKBOX = "(" + CONDITIONS_APPROVAL_ROW_WITH_VALIDITY + ")[%s]";

    String SAVE_BUTTON = CONDITIONS_APPROVAL_TABLE + "//input[@value='Návrat s uložením']";

    @CustomAction
    default DrawingConditionsApprovalPage approveDrawingConditions() {
        HyposEndpoint endpoint = getEndpoint(HyposEndpoint.class);
        List<WebElement> conditionRows = endpoint.findAndGetListOfElements(CONDITIONS_APPROVAL_ROW, Lookup.XPATH);
        for (int i = 1; i <= conditionRows.size(); i++) {
            int rowIndex = i;
            endpoint.click(() -> String.format(CONDITION_CHECK_CHECKBOX, rowIndex));
            endpoint.waitForElementsToLoad(20, Until.GONE, LOADER);
        }
        List<WebElement> conditionRowsWithDate = endpoint.findAndGetListOfElements(CONDITIONS_APPROVAL_ROW_WITH_VALIDITY, Lookup.XPATH);
        for (int i = 1; i <= conditionRowsWithDate.size(); i++) {
            int rowIndex = i;
            endpoint.click(() -> String.format(CONDITION_VALIDITY_UNLIMITED_CHECKBOX, rowIndex));
        }
        return null;
    }

    @CustomAction
    default DrawingConditionsApprovalPage approveMortgageConditions() {
        HyposEndpoint endpoint = getEndpoint(HyposEndpoint.class);
        List<WebElement> conditionRows = endpoint.findAndGetListOfElements(CONDITIONS_APPROVAL_ROW, Lookup.XPATH);
        for (int i = 1; i <= conditionRows.size(); i++) {
            int rowIndex = i;
            endpoint.click(() -> String.format(CONDITION_CHECK_CHECKBOX, rowIndex));
        }
        return null;
    }

    @Click(SAVE_BUTTON)
    LoanPage clickSaveAndReturnButton();
}