package cz.moneta.test.dsl.monetaportal.products;

import cz.moneta.test.harness.context.StoreAccessor;
import cz.moneta.test.harness.endpoints.MonetaPortalEndpoint;
import cz.moneta.test.harness.support.web.*;
import org.junit.jupiter.api.Assertions;
import org.openqa.selenium.WebElement;

import java.util.List;


@Waits({@Wait(InvestmentFundsPage.FILTER_FORM_WRAPPER), @Wait(InvestmentFundsPage.RISK_FILTER_SELECT)})
public interface InvestmentFundsPage extends WebFlow<InvestmentFundsPage>, StoreAccessor {
    String FILTER_FORM_WRAPPER = "//mutual-funds-widget";
    String GO_TO_FUND_DETAIL_BUTTON = "(//*[@data-message-id='list.btnFundDetail'])"; // "*" because it was changed soo many times
    String GO_TO_FUND_DETAIL_BUTTON_BY_ORDER = GO_TO_FUND_DETAIL_BUTTON + "[%s]";
    String RISK_FILTER_SELECT = FILTER_FORM_WRAPPER + "//div[@data-name='risk']";
    String FILTER_OPTION_BY_VALUE = FILTER_FORM_WRAPPER + "//*[@role = 'option' and .//*[contains(text(),'%s')]]";
    String FILTER_OPTION = FILTER_FORM_WRAPPER + "//*[@role = 'option']";
    String All_FILTERS = "//span[@data-message-id='form.allFilters']";
    String FILTER_SELECTS = FILTER_FORM_WRAPPER + "//div[@role='combobox']";
    String ALL_FUNDS_BUTTON = "//button[.//*[@data-message-id='btnAllFunds']]";

    @Click(value = GO_TO_FUND_DETAIL_BUTTON_BY_ORDER, jsClick = true, isStringDynamicXpath = true)
    InvestmentFundDetailPage clickFundByOrder(String order);

    @Click(RISK_FILTER_SELECT)
    InvestmentFundsPage clickRiskFilterSelect();

    @Click(value = All_FILTERS, jsClick = true)
    InvestmentFundsPage clickAllFilters();

    @Click(value = ALL_FUNDS_BUTTON, jsClick = true)
    InvestmentFundsPage clickAllFunds();

    @Click(value = FILTER_OPTION_BY_VALUE, jsClick = true, isStringDynamicXpath = true)
    InvestmentFundsPage clickOptionByValue(String value);

    @CustomAction
    default InvestmentFundsPage checkAllFilters() {
        MonetaPortalEndpoint e = getEndpoint(MonetaPortalEndpoint.class);
        clickAllFilters();
        List<WebElement> filters = e.findAndGetListOfElements(FILTER_SELECTS, Lookup.XPATH);
        filters.forEach(filterSelect -> {
            int listedFundNumberBefore = e.findAndGetListOfElements(GO_TO_FUND_DETAIL_BUTTON, Lookup.XPATH).size();
            filterSelect.click();
            e.jsClick(() -> "(" + FILTER_OPTION + ")" + "[2]", Lookup.XPATH);
            int listedFundNumberAfter = e.findAndGetListOfElements(GO_TO_FUND_DETAIL_BUTTON, Lookup.XPATH).size();
            Assertions.assertTrue(listedFundNumberBefore > listedFundNumberAfter);
            clickAllFunds();
        });
        return null;
    }

}
