package cz.moneta.test.dsl.ib.account.current;

import cz.moneta.test.dsl.ib.IbPageFlow;
import cz.moneta.test.dsl.ib.components.AccountsAndTransactionsSubmenu;
import cz.moneta.test.dsl.ib.components.MainMenu;
import cz.moneta.test.harness.context.StoreAccessor;
import cz.moneta.test.harness.endpoints.ib.IbEndpoint;
import cz.moneta.test.harness.exception.HarnessException;
import cz.moneta.test.harness.support.web.*;
import org.junit.jupiter.api.Assertions;
import org.openqa.selenium.WebElement;

import java.util.List;

import static cz.moneta.test.dsl.ib.account.current.CurrentAccountPage.CURRENT_ACCOUNT_LIST_HEADER;

@Wait(value = CURRENT_ACCOUNT_LIST_HEADER, waitSecondsForElement = 40)
public interface CurrentAccountPage extends IbPageFlow<CurrentAccountPage>, MainMenu, AccountsAndTransactionsSubmenu, StoreAccessor {

    String CURRENT_ACCOUNT_LIST_HEADER = "//div[@id='document']//img[contains(@src, 'prehled_beznych_uctu.gif')]";
    String FIRST_ACCOUNT_CELL = "//div[@id='document']//table[@id='balanceList_1_1']//tr[@class='listBodyOdd']";
    String AVAILABLE_BALANCE_XPATH = "//td[@class='listItemBold listBodyOdd']";
    String AVAILABLE_BALANCE_VALUE_KEY = "AVAILABLE_BALANCE_VALUE";
    String ACCOUNTS = "//span[@class='account listBodyOdd']/a";
    String FLEXICREDIT_AMOUNT = "//a[contains(text(), '%s')]//ancestor::tr[contains(@id, 'a')]//span[contains(text(), 'částka je včetně kontokorentu')]//following-sibling::span";

    @CheckElementPresent(FIRST_ACCOUNT_CELL)
    CurrentAccountPage checkUserHasACurrentAccount();

    @StoreElementContent(storeKey = AVAILABLE_BALANCE_VALUE_KEY, value = AVAILABLE_BALANCE_XPATH, by = Lookup.XPATH)
    CurrentAccountPage getAvailableBalance();

    @CustomAction
    default CurrentAccountPage verifyFlexiCreditAmount(String account, String expectedFlexiAmount) {
        IbEndpoint endpoint = getEndpoint(IbEndpoint.class);
        String actualFlexiAmount = endpoint.getText(String.format(FLEXICREDIT_AMOUNT, account)).replaceAll("Kč| ", "");
        if (!expectedFlexiAmount.contains(actualFlexiAmount)) {
            throw new HarnessException("Actual amount is not equals to expected amount");
        }
        return null;
    }

    @CustomAction
    default CurrentAccountPage checkExistJustCurrentAccount(String currentAccountNumber) {
        IbEndpoint endpoint = getEndpoint(IbEndpoint.class);
        int expectedAccounts = 1;
        List<WebElement> listAccountElements = endpoint.findAndGetListOfElements(ACCOUNTS, Lookup.XPATH);
        boolean isCurrentAccountExist = listAccountElements.stream()
                .anyMatch(s -> s.getText().contains(currentAccountNumber));

        Assertions.assertTrue(isCurrentAccountExist, "Expected account name is " + currentAccountNumber);
        Assertions.assertEquals(expectedAccounts, listAccountElements.size(), "Expected number of accounts is " + expectedAccounts);

        return null;
    }
}