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.TypeInto;
import cz.moneta.test.harness.support.web.Wait;

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

@Wait({PAGE_TITLE, SAVE_BUTTON})
public interface NewTransactionPage extends HyposPageFlow<NewTransactionPage>, StoreAccessor {
    String PAGE_TITLE = "//h2[text()='Zadání tranší']";
    String TRANCHE_TABLE = "//table[@id='subTranche']";
    String LOAN_AMOUNT_INPUT = "//input[@id='amount%s']";
    String LOAN_TYPE_SELECT = "//select[@id='purposeId%s']";
    String PAYMENT_TYPE_SELECT = "//select[@id='paymentTypeId%s']";
    String TRANCHE_INPUT = "//input[@id='trancheOrder%s']";
    String ADD_TRANCHE_BUTTON = TRANCHE_TABLE + "//a[contains(text(), 'Přidat další tranši')]";
    String SAVE_BUTTON = TRANCHE_TABLE + "//input[@value='Uložit']";

    @TypeInto(value = LOAN_AMOUNT_INPUT, clear = true)
    NewTransactionPage fillLoanAmount(int loanAmount);

    @Click(SAVE_BUTTON)
    LoanPage clickSaveButton();

    @CustomAction
    default NewTransactionPage addTranches(HyposContract hyposContract) {
        HyposEndpoint endpoint = getEndpoint(HyposEndpoint.class);
        for (int i = 0; i < hyposContract.getLoanPurposes().size(); i++) {
            String tranche = String.valueOf(i);
            endpoint.selectByValue(String.format(LOAN_TYPE_SELECT, tranche), hyposContract.getLoanPurposes().get(i).getType());
            endpoint.type(() -> String.format(LOAN_AMOUNT_INPUT, tranche), hyposContract.getLoanPurposes().get(i).getAmount(), true);
            endpoint.type(() -> String.format(TRANCHE_INPUT, tranche), hyposContract.getLoanPurposes().get(i).getTranche(), true);
            if(!hyposContract.getLoanPurposes().get(i).getType().equals("1")) {
                endpoint.selectByValue(String.format(PAYMENT_TYPE_SELECT, tranche), hyposContract.getLoanPurposes().get(i).getPaymentType());
            }
            if(hyposContract.getLoanPurposes().size() > i + 1) {
                endpoint.click(() -> ADD_TRANCHE_BUTTON);
            }
        }
        return null;
    }
}