package cz.moneta.test.dsl.salesforce.pages;

import cz.moneta.test.dsl.salesforce.pages.accounts.AccountDetailPage;
import cz.moneta.test.harness.context.StoreAccessor;
import cz.moneta.test.harness.endpoints.sales_force.SalesForceEndpoint;
import cz.moneta.test.harness.support.web.*;

import static cz.moneta.test.dsl.salesforce.pages.SearchPage.SEARCH_RESULTS_HEADER;
import static cz.moneta.test.dsl.salesforce.pages.SearchPage.SEARCH_RESULTS_WINDOW;

@Wait(value = {SEARCH_RESULTS_HEADER, SEARCH_RESULTS_WINDOW}, until = Until.VISIBLE)
public interface SearchPage extends WebFlow<SearchPage>, StoreAccessor {
    String SEARCH_RESULTS_HEADER = "//h1[text()='Výsledky hledání']";
    String SEARCH_RESULTS_WINDOW = "//div[contains(@class,'predictedResultsScrollWrapper')]";

    String ACCOUNTS_DIV = "//div[@class='slds-grid slds-grid_vertical']";
    String ACCOUNT_DETAIL_LINK = ACCOUNTS_DIV + "//td[contains(.,'%s')]/../th/span/a";
    String SEARCH_INPUT = "(//div[@class='forceSearchAssistantDialog']//input)[2]";
    String SEARCH_BUTTON = "//div[contains(@class,'global-header__item_search')]//button";

    @Click(value = ACCOUNT_DETAIL_LINK, isStringDynamicXpath = true)
    AccountDetailPage clickAccountDetail(String account);

    @CustomAction
    default AccountDetailPage clickAccountDetailOrTrySearchAgain(String account, Integer timeout) {
        SalesForceEndpoint endpoint = getEndpoint(SalesForceEndpoint.class);
        endpoint.waitForElementAndRefresh(
                String.format(ACCOUNT_DETAIL_LINK, account),
                Lookup.XPATH,
                () -> {
                    endpoint.click(() -> SEARCH_BUTTON);
                    endpoint.type(() -> SEARCH_INPUT, account, true);
                    endpoint.sendKeysOneAtATime(Key.ENTER);
                },
                timeout,
                5
        );
        endpoint.click(() -> String.format(ACCOUNT_DETAIL_LINK, account), Lookup.XPATH);
        return null;
    }
}
