package cz.moneta.test.dsl.monetaportal.savings.childbuildingsavings;

import cz.moneta.test.harness.endpoints.ib.NewIbEndpoint;
import cz.moneta.test.harness.support.web.*;

import static cz.moneta.test.dsl.monetaportal.savings.childbuildingsavings.CalculatorPage.PAGE_HEADER;

@Wait(PAGE_HEADER)
public interface CalculatorPage extends ChildBuildingSavingsPageFlow<CalculatorPage> {
    String PAGE_HEADER = "//h2[text()='Nastavte parametry stavebního spoření']";
    String SLIDER = "/following-sibling::div[@class='f-slider u-mb--medium'][1]/";
    String SLIDER_DRAG = "/div[@class='f-slider__drag']";
    String SLIDER_HANDLE = "/div[@class='f-slider__handle']";
    String MONTH_PAYMENT = "//*[@id='monthlyPayment']";
    String TERM_LABEL = "//div[./div[text()='Doba spoření']]";
    String TERM_SLIDER_DRAG = TERM_LABEL + SLIDER + SLIDER_DRAG;
    String TERM_SLIDER_HANDLE = TERM_LABEL + SLIDER + SLIDER_DRAG + SLIDER_HANDLE;
    String TARGET_AMOUNT = "//*[@id='targetAmount']";
    String STATE_SUPPORT_INPUT = "//*[@id='stateSupport']";
    String STATE_SUPPORT_LABEL = "//*[@for='stateSupport']";

    @TypeInto(value = MONTH_PAYMENT, clear = true)
    CalculatorPage setPayment(String monthPayment);

    @CustomAction
    default CalculatorPage setTerm(String value) {
        dragAndDropSlider(TERM_SLIDER_DRAG, TERM_SLIDER_HANDLE, value);
        return null;
    }

    @TypeInto(value = TARGET_AMOUNT, clear = true)
    CalculatorPage setTargetAmount(String targetAmount);

    @Click(STATE_SUPPORT_LABEL)
    CalculatorPage clickStateSupport();

    @CustomAction
    default CalculatorPage setStateSupport(boolean isStateSupport) {
        NewIbEndpoint ep = getEndpoint(NewIbEndpoint.class);
        boolean isChecked = ep.getAttribute(STATE_SUPPORT_INPUT, "value").equals("true");
        if (isStateSupport != isChecked) clickStateSupport();
        return null;
    }

    @Click(CONTINUE_BUTTON)
    ConsentsPage clickContinue();

    private void dragAndDropSlider(String dragXpath, String handleXpath, String value) {
        NewIbEndpoint ep = getEndpoint(NewIbEndpoint.class);

        String defaultValue = ep.getAttribute(dragXpath, "aria-valuenow");
        double minValue = Integer.parseInt(ep.getAttribute(dragXpath, "aria-valuemin"));
        double maxValue = Integer.parseInt(ep.getAttribute(dragXpath, "aria-valuemax"));
        double maxOffset = ep.findAndGetListOfElements(dragXpath, Lookup.XPATH).stream().findFirst().get().getSize().width;
        double intValue = Double.parseDouble(value);
        double offset = maxOffset / (maxValue - minValue) * (intValue - Double.parseDouble(defaultValue));

        ep.dragAndDropBy(handleXpath, (int) offset, 0);
    }
}
