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

import cz.moneta.test.dsl.hypos.pages.HyposPageFlow;
import cz.moneta.test.dsl.util.data.hypos.HyposContract;
import cz.moneta.test.harness.context.StoreAccessor;
import cz.moneta.test.harness.endpoints.hypos.HyposEndpoint;
import cz.moneta.test.harness.support.web.Click;
import cz.moneta.test.harness.support.web.CustomAction;
import cz.moneta.test.harness.support.web.Until;
import cz.moneta.test.harness.support.web.Wait;

import static cz.moneta.test.dsl.hypos.pages.contract.loan.DrawingConditionsPage.ASSIGNED_DIV;
import static cz.moneta.test.dsl.hypos.pages.contract.loan.DrawingConditionsPage.AVAILABLE_DIV;
import static cz.moneta.test.dsl.hypos.pages.contract.loan.DrawingConditionsPage.PAGE_TITLE;

@Wait({PAGE_TITLE, AVAILABLE_DIV, ASSIGNED_DIV})
public interface DrawingConditionsPage extends HyposPageFlow<DrawingConditionsPage>, StoreAccessor {
    String PAGE_TITLE = "//h1[text()='Volba podmínky']";
    String AVAILABLE_DIV = "//div[@id='available']";
    String ASSIGNED_DIV = "//div[@id='assigned']";
    String CONDITION = "(" + AVAILABLE_DIV + "//td[contains(text(),'%s')])[1]";
    String CONDITION_CHECKBOX = "(" + ASSIGNED_DIV + "//a[contains(text(),'%1$s')]/following::td[1]/div/input)[%2$s]";
    String RETURN_LINK = "//a[text()='Návrat']";

    @CustomAction
    default DrawingConditionsPage moveAndCheckConditions(HyposContract hyposContract) {
        HyposEndpoint endpoint = getEndpoint(HyposEndpoint.class);
        for (int i = 0; i < hyposContract.getDrawingConditions().size(); i++) {
            String conditionTd = String.format(CONDITION, hyposContract.getDrawingConditions().get(i).getCondition());
            endpoint.waitForElementsToLoad(60, Until.VISIBLE, conditionTd);
            endpoint.scrollIntoView(conditionTd);
            endpoint.dragAndDropBy(conditionTd, 1000, 0);
            endpoint.waitForElementsToLoad(60, Until.GONE, HyposPageFlow.LOADER);

            if (hyposContract.getDrawingConditions().get(i).getTranches() != null) {
                for (int j = 0; j < hyposContract.getDrawingConditions().get(i).getTranches().size(); j++) {
                    String conditionTranche = String.format(CONDITION_CHECKBOX, hyposContract.getDrawingConditions().get(i).getCondition(), hyposContract.getDrawingConditions().get(i).getTranches().get(j));
                    endpoint.click(() -> conditionTranche);
                }
            }
        }
        return null;
    }

    @Click(RETURN_LINK)
    LoanPage clickReturnButton();
}