package cz.moneta.test.regression.channels.digital.ib.oldib.disponents;

import cz.moneta.test.dsl.Harness;
import cz.moneta.test.dsl.ib.settings.ib.ediponents.ConfirmSetDiponentPage;
import cz.moneta.test.dsl.ib.settings.ib.ediponents.DisponentsOverview;
import cz.moneta.test.dsl.ib.welcome.WelcomePage;
import cz.moneta.test.dsl.util.task.ib.IbTasks;
import cz.moneta.test.harness.annotations.JiraTestCase;
import cz.moneta.test.harness.annotations.TestCase;
import cz.moneta.test.harness.annotations.TestScenarioWithOrder;
import cz.moneta.test.harness.endpoints.ib.IbEndpoint;
import cz.moneta.test.harness.support.auth.Credentials;
import cz.moneta.test.harness.support.web.Lookup;
import org.junit.jupiter.api.*;

import java.util.Arrays;
import java.util.List;

import static cz.moneta.test.dsl.util.task.ib.IbTasks.DEFAULT_MOBILE_KEY;
import static cz.moneta.test.harness.annotations.Environment.PPE;
import static cz.moneta.test.harness.annotations.Environment.TST1;

@TestScenarioWithOrder(name = "Test scenario to set disponents rights and send payments")
public class DisponentsTest {
    private Credentials mainUserCredentials;
    private Credentials activeUserCredentials;
    private Credentials pasiveUserCredentials;
    private String clientIdManinUser;
    private String SAVING_ACCOUNT = "Spořicí účet";
    private String CURRENT_ACCOUNT = "Běžný účet";
    private String EXPRESS_ACCOUNT = "Expres";
    private String AUTOMATICLLY_ADDED_NEW_ACCOUNT = "Automaticky přidávat nové účty";
    private String LIMIT = "50000";
    private String OPERID_CHANGE_RIGHTS = "471";
    private String EXPECTED_STATUS_CHANGE_RIGHTS = "60";
    private String CHANNEL_ID = "15";
    private String ACCOUNT_NUMBER_TO_SEND = "123";
    private String ACCOUNT_BANK_TO_SEND = "0600";
    private String AMOUNT_TO_SEND = "1";
    private String statusTransactionActiveUser;
    private String statusTransactionPasiveUser;
    private String currentAccountNumber;
    private String activeDisponentName;
    private String pasiveDisponentName;
    private String mainUserName;
    private boolean isActiveSetRightsToMinimum;
    private boolean isPasiveSetRightsToMinimum;
    private boolean isActiveSetAutomaticllyAddedNewAccount;
    private boolean isPasiveSetAutomaticllyAddedNewAccount;

    private Credentials getCredentialsByRc(Harness harness, String keyInConfigForBirthNumber) {
        String clientBirthNumber = harness.getConfig(keyInConfigForBirthNumber);
        return harness.tasks()
                .udebs()
                .findCredentialsByRC(clientBirthNumber);
    }

    @BeforeAll
    public void prepareDataForTests(Harness harness) {
        mainUserCredentials = getCredentialsByRc(harness, "IB.rc.diponents-main-user");
        activeUserCredentials = getCredentialsByRc(harness, "IB.rc.diponents-active-user");
        pasiveUserCredentials = getCredentialsByRc(harness, "IB.rc.diponents-pasive-user");
        currentAccountNumber = harness.getConfig("IB.rc.diponents-current-account-number");

        clientIdManinUser = harness.withUdebs()
                .usersTable()
                .getClientId(harness.getConfig("IB.rc.diponents-main-user"));

    }

    @Disabled
    @Order(1)
    @TestCase(name = "Test case for set disponents rights to minimum level", environments = {TST1, PPE})
    @JiraTestCase(id = "IB-T8533")
    public void setDisponibileRightsToMinimum(Harness harness) {
        IbTasks ibTasks = harness.tasks().ib();

        DisponentsOverview activeDisponent = harness.withIB()
                .openLoginPage()
                .then(ibTasks.loginWithDefaultMobileKeyAnd(mainUserCredentials))
                .getNameFromWelcomePage()
                .goToSettings()
                .clickToEdisponentsAdministration()
                .getActiveDisponentName(activeUserCredentials.getUsername())
                .chooseDisponent(activeUserCredentials.getUsername())
                .clickToChangeSettings()
                .rightsForAccountsClicksToCheckboxes(Arrays.asList(SAVING_ACCOUNT, EXPRESS_ACCOUNT))
                .clickToContinueButtonWithoutSelection()
                .accpetAlertWindow()
                .clickCheckboxPaymentsLimits()
                .typeLimit(LIMIT)
                .rightsForAccountsClickToCheckbox(CURRENT_ACCOUNT)
                .clickToContinueButton()
                .checkPaymentLimit(LIMIT)
                .checkSetAccountName(CURRENT_ACCOUNT)
                .fillInMobileKey(DEFAULT_MOBILE_KEY)
                .clickSign()
                .clickOverviewDisponents();

        isActiveSetRightsToMinimum = true;

        statusTransactionActiveUser = harness.withUdebs()
                .transactionsClient()
                .getLastTransactionStatus(clientIdManinUser, OPERID_CHANGE_RIGHTS, CHANNEL_ID, 60, EXPECTED_STATUS_CHANGE_RIGHTS);
        Assertions.assertEquals(EXPECTED_STATUS_CHANGE_RIGHTS, statusTransactionActiveUser, "Status of transacaction for active disponent ");

        activeDisponent.clickToDetail(activeUserCredentials.getUsername())
                .checkRightsForAccountAndSmartBank(CURRENT_ACCOUNT);

        DisponentsOverview pasiveDisponent = harness.withIB()
                .openLoginPage()
                .then(ibTasks.loginWithDefaultMobileKeyAnd(mainUserCredentials))
                .goToSettings()
                .clickToEdisponentsAdministration()
                .getPasiveDisponentName(pasiveUserCredentials.getUsername())
                .chooseDisponent(pasiveUserCredentials.getUsername())
                .clickToChangeSettings()
                .rightsForAccountsClicksToCheckboxes(Arrays.asList(AUTOMATICLLY_ADDED_NEW_ACCOUNT, CURRENT_ACCOUNT, SAVING_ACCOUNT, EXPRESS_ACCOUNT))
                .clickToContinueButtonWithoutSelection()
                .accpetAlertWindow()
                .rightsForAccountsClickToCheckbox(CURRENT_ACCOUNT)
                .clickToContinueButton()
                .checkSetAccountName(CURRENT_ACCOUNT)
                .fillInMobileKey(DEFAULT_MOBILE_KEY)
                .clickSign()
                .clickOverviewDisponents();

        isPasiveSetRightsToMinimum = true;

        statusTransactionPasiveUser = harness.withUdebs()
                .transactionsClient()
                .getLastTransactionStatus(clientIdManinUser, OPERID_CHANGE_RIGHTS, CHANNEL_ID, 60, EXPECTED_STATUS_CHANGE_RIGHTS);
        Assertions.assertEquals(EXPECTED_STATUS_CHANGE_RIGHTS, statusTransactionPasiveUser, "Status of transacaction for pasive disponent");

        pasiveDisponent.clickToDetail(pasiveUserCredentials.getUsername())
                .checkRightsForAccountAndSmartBank(CURRENT_ACCOUNT);

    }

    @Disabled
    @Order(2)
    @TestCase(name = "Test case for check disponents rights and payments", environments = {TST1, PPE})
    @JiraTestCase(id = "IB-T8534")
    public void checkDisponentsRightsAndPayments(Harness harness) {
        List<String> notClickableMenuItemsActive = Arrays.asList("Spoření", "karty", "Půjčky", "Hypotéky");
        List<String> notClickableMenuItemsPasive = Arrays.asList("Spoření", "karty", "Půjčky", "Hypotéky", "Investování");
        IbTasks ibTasks = harness.tasks().ib();

        Assertions.assertTrue(isActiveSetRightsToMinimum && isPasiveSetRightsToMinimum, "One of disponents or both did not have set rights in setDisponibileRightsToMinimum");

        WelcomePage activeDisponentWelcomePage = harness.withIB()
                .openLoginPage()
                .then(ibTasks.loginWithDefaultMobileKeyAnd(activeUserCredentials))
                .checkAndConfirmCookies()
                .getNameFromWelcomePage();

        activeDisponentName = harness.get("MY_NAME").toString().trim();

        activeDisponentWelcomePage
                .checkMainMenuItemsIsNotClickable(notClickableMenuItemsActive)
                .clickAccountsAndTransactions()
                .checkExistJustCurrentAccount(currentAccountNumber)
                .then(ibTasks.paymentsIbTasks().preparePaymentToSignatureFromActiveDisponent(CURRENT_ACCOUNT, ACCOUNT_NUMBER_TO_SEND, ACCOUNT_BANK_TO_SEND, AMOUNT_TO_SEND))
                .then(ibTasks.paymentsIbTasks().preparePaymentToSignatureFromActiveDisponent(CURRENT_ACCOUNT, ACCOUNT_NUMBER_TO_SEND, ACCOUNT_BANK_TO_SEND, AMOUNT_TO_SEND))
                .then(ibTasks.paymentsIbTasks().preparePaymentToSignatureFromActiveDisponent(CURRENT_ACCOUNT, ACCOUNT_NUMBER_TO_SEND, ACCOUNT_BANK_TO_SEND, AMOUNT_TO_SEND))
                .then(ibTasks.paymentsIbTasks().rejectPaymentForSignature(activeDisponentName))
                .clickPaymentsWaitingForSignature()
                .selectAuthorPaymentAndClickShowButton(activeDisponentName)
                .selectAuthorPaymentAndClickShowButton(activeDisponentName)
                .selectFirstPayment()
                .clickSignSelectedButton()
                .clickSign()
                .typeSmsCode(DEFAULT_MOBILE_KEY)
                .clickSignSms()
                .clickNewDomesticPaymentOrder()
                .selectFromAccountByName(CURRENT_ACCOUNT)
                .fillToAccountNumber(ACCOUNT_NUMBER_TO_SEND)
                .fillToAccountBank(ACCOUNT_BANK_TO_SEND)
                .fillAmount(AMOUNT_TO_SEND)
                .clickInstantPayment()
                .clickContinueButton()
                .clickSign()
                .typeSmsCode(DEFAULT_MOBILE_KEY)
                .clickSend();

        WelcomePage pasiveDisponentWelcomePage = harness.withIB()
                .openLoginPage()
                .then(ibTasks.loginWithDefaultMobileKeyAnd(pasiveUserCredentials))
                .checkAndConfirmCookies()
                .getNameFromWelcomePage();

        pasiveDisponentName = harness.get("MY_NAME").toString().trim();

        pasiveDisponentWelcomePage
                .checkMainMenuItemsIsNotClickable(notClickableMenuItemsPasive)
                .clickAccountsAndTransactions()
                .checkExistJustCurrentAccount(currentAccountNumber)
                .then(ibTasks.paymentsIbTasks().preparePaymentToSignatureFromPasiveDisponent(CURRENT_ACCOUNT, ACCOUNT_NUMBER_TO_SEND, ACCOUNT_BANK_TO_SEND, AMOUNT_TO_SEND))
                .then(ibTasks.paymentsIbTasks().preparePaymentToSignatureFromPasiveDisponent(CURRENT_ACCOUNT, ACCOUNT_NUMBER_TO_SEND, ACCOUNT_BANK_TO_SEND, AMOUNT_TO_SEND))
                .then(ibTasks.paymentsIbTasks().preparePaymentToSignatureFromPasiveDisponent(CURRENT_ACCOUNT, ACCOUNT_NUMBER_TO_SEND, ACCOUNT_BANK_TO_SEND, AMOUNT_TO_SEND))
                .then(ibTasks.paymentsIbTasks().rejectPaymentForSignature(pasiveDisponentName));
    }

    @Disabled
    @Order(3)
    @TestCase(name = "Login to main user account and sign payments", environments = {TST1, PPE})
    @JiraTestCase(id = "IB-T8535")
    public void loginToMainUserAndSignPayments(Harness harness) {
        IbTasks ibTasks = harness.tasks().ib();

        Assertions.assertTrue(isActiveSetRightsToMinimum && isPasiveSetRightsToMinimum, "One of disponents or both did not have set rights in setDisponibileRightsToMinimum and did not prepare payments");

        WelcomePage mainUserWelcomePage = harness.withIB()
                .openLoginPage()
                .then(ibTasks.loginWithDefaultMobileKeyAnd(mainUserCredentials))
                .getNameFromWelcomePage();

        mainUserName = harness.get("MY_NAME").toString().trim();

        mainUserWelcomePage
                .clickAccountsAndTransactions()
                .then(ibTasks.paymentsIbTasks().preparePaymentToSignatureFromActiveDisponent(CURRENT_ACCOUNT, ACCOUNT_NUMBER_TO_SEND, ACCOUNT_BANK_TO_SEND, AMOUNT_TO_SEND))
                .then(ibTasks.paymentsIbTasks().preparePaymentToSignatureFromActiveDisponent(CURRENT_ACCOUNT, ACCOUNT_NUMBER_TO_SEND, ACCOUNT_BANK_TO_SEND, AMOUNT_TO_SEND))
                .clickPaymentsWaitingForSignature()
                .selectFirstPaymentByAuthor(mainUserName)
                .selectFirstPaymentByAuthor(activeDisponentName)
                .selectFirstPaymentByAuthor(pasiveDisponentName)
                .clickSignSelectedButton()
                .clickSign()
                .typeSmsCode(DEFAULT_MOBILE_KEY)
                .clickSignSms();
    }

    @Disabled
    @Order(4)
    @TestCase(name = "Login to active user account and sign payments", environments = {TST1, PPE})
    @JiraTestCase(id = "IB-T8536")
    public void loginToActiveUserAndSignPayments(Harness harness) {
        IbTasks ibTasks = harness.tasks().ib();

        Assertions.assertTrue(isActiveSetRightsToMinimum && isPasiveSetRightsToMinimum, "One of disponents or both did not have set rights in setDisponibileRightsToMinimum and did not prepare payments");

        harness.withIB()
                .openLoginPage()
                .then(ibTasks.loginWithDefaultMobileKeyAnd(activeUserCredentials))
                .getNameFromWelcomePage()
                .clickAccountsAndTransactions()
                .clickPaymentsWaitingForSignature()
                .selectFirstPaymentByAuthor(mainUserName)
                .selectFirstPaymentByAuthor(pasiveDisponentName)
                .clickSignSelectedButton()
                .clickSign()
                .typeSmsCode(DEFAULT_MOBILE_KEY)
                .clickSignSms();
    }

    @Disabled
    @Order(5)
    @TestCase(name = "Login to main user account, change and check rights for disponents", environments = {TST1, PPE})
    @JiraTestCase(id = "IB-T8537")
    public void changeDispinentsRight(Harness harness) {
        IbTasks ibTasks = harness.tasks().ib();
        List<String> automaticllyAddedNewAccount = Arrays.asList(AUTOMATICLLY_ADDED_NEW_ACCOUNT);
        List<String> mainMenuItemsToCheck = Arrays.asList("Spoření", "Půjčky");

        ConfirmSetDiponentPage mainUserConfirmSetDisponentPage = harness.withIB()
                .openLoginPage()
                .then(ibTasks.loginWithDefaultMobileKeyAnd(mainUserCredentials))
                .then(ibTasks.disponentsRightsIbTasks().mainUserSetDisponentsRights(activeUserCredentials.getUsername(), automaticllyAddedNewAccount));

        isActiveSetAutomaticllyAddedNewAccount = true;

        mainUserConfirmSetDisponentPage
                .clickToWelcomePageButton()
                .then(ibTasks.disponentsRightsIbTasks().mainUserSetDisponentsRights(pasiveUserCredentials.getUsername(), automaticllyAddedNewAccount));

        isPasiveSetAutomaticllyAddedNewAccount = true;

        harness.withIB()
                .openLoginPage()
                .then(ibTasks.loginWithDefaultMobileKeyAnd(activeUserCredentials))
                .checkMainMenuItemsIsClickable(mainMenuItemsToCheck);

        harness.withIB()
                .openLoginPage()
                .then(ibTasks.loginWithDefaultMobileKeyAnd(pasiveUserCredentials))
                .checkMainMenuItemsIsClickable(mainMenuItemsToCheck);
    }

    @Disabled
    @Order(6)
    @TestCase(name = "Login to main user account, change and check rights for disponents", environments = {TST1, PPE})
    @JiraTestCase(id = "IB-T8538")
    public void testToDeactivateDisponents(Harness harness) {
        IbTasks ibTasks = harness.tasks().ib();

        harness.withIB()
                .openLoginPage()
                .then(ibTasks.loginWithDefaultMobileKeyAnd(mainUserCredentials))
                .goToSettings()
                .clickToEdisponentsAdministration()
                .chooseDisponent(activeUserCredentials.getUsername())
                .clickDeactiveDisponentButton()
                .checkDeactiveStatusAndClickToContinue()
                .checkDeactiveStatusAndSign()
                .clickOverviewDisponents()
                .chooseDisponent(pasiveUserCredentials.getUsername())
                .clickDeactiveDisponentButton()
                .checkDeactiveStatusAndClickToContinue()
                .checkDeactiveStatusAndSign()
                .clickOverviewDisponents()
                .clickLogOff();

        harness.withIB()
                .openLoginPage()
                .then(ibTasks.loginWithUsernamePasswordAndMobileKey(activeUserCredentials.getUsername(), activeUserCredentials.getPassword(), DEFAULT_MOBILE_KEY))
                .onNonactiveDisponentWelcomePage()
                .checkInformationTextToNonactiveDisponentPage();

        harness.withIB()
                .openLoginPage()
                .then(ibTasks.loginWithUsernamePasswordAndMobileKey(pasiveUserCredentials.getUsername(), pasiveUserCredentials.getPassword(), DEFAULT_MOBILE_KEY))
                .onNonactiveDisponentWelcomePage()
                .checkInformationTextToNonactiveDisponentPage();
    }

    private void activateInactiveDisponents(Harness harness) {
        IbTasks ibTasks = harness.tasks().ib();
        String ACTIVATE_EDISPONENT = "//input[@value='%s']/ancestor::td[@class='listItem']/following-sibling::td[contains(text(),'Neaktivní')]";

        DisponentsOverview disponentsOverview = harness.withIB()
                .openLoginPage()
                .then(ibTasks.loginWithDefaultMobileKeyAnd(mainUserCredentials))
                .goToSettings()
                .clickToEdisponentsAdministration();

        IbEndpoint ibEndpoint = harness.getEndpoint(IbEndpoint.class);
        if (ibEndpoint.isElementPresent(String.format(ACTIVATE_EDISPONENT, activeUserCredentials.getUsername()), Lookup.XPATH)) {
            disponentsOverview.chooseDisponent(activeUserCredentials.getUsername())
                    .clickActivateDisponentButton()
                    .checkActiveStatusAndClickToContinue()
                    .checkActiveStatusAndSign()
                    .clickOverviewDisponents();
        }

        if (ibEndpoint.isElementPresent(String.format(ACTIVATE_EDISPONENT, pasiveUserCredentials.getUsername()), Lookup.XPATH)) {
            disponentsOverview.chooseDisponent(pasiveUserCredentials.getUsername())
                    .clickActivateDisponentButton()
                    .checkActiveStatusAndClickToContinue()
                    .checkActiveStatusAndSign()
                    .clickOverviewDisponents();
        }

        disponentsOverview.clickLogOff();
    }

    private void revertRightsForDisponent(Harness harness, String usernameDisponent, List<String> namesOfItemsToClickCheckboxes) {
        IbTasks ibTasks = harness.tasks().ib();

        harness.withIB()
                .openLoginPage()
                .then(ibTasks.loginWithDefaultMobileKeyAnd(mainUserCredentials))
                .goToSettings()
                .clickToEdisponentsAdministration()
                .chooseDisponent(usernameDisponent)
                .clickToChangeSettings()
                .rightsForAccountsClicksToCheckboxes(namesOfItemsToClickCheckboxes)
                .clickToContinueButton()
                .fillInMobileKey(DEFAULT_MOBILE_KEY)
                .clickSign();
    }

    @AfterAll
    public void revertDisponibileRight(Harness harness) {
        activateInactiveDisponents(harness);

        if (isActiveSetRightsToMinimum && !isActiveSetAutomaticllyAddedNewAccount) {
            List<String> nameOfItemsToClicks = Arrays.asList(SAVING_ACCOUNT, EXPRESS_ACCOUNT, CURRENT_ACCOUNT);
            revertRightsForDisponent(harness, activeUserCredentials.getUsername(), nameOfItemsToClicks);
            harness.log("Rights to active disponent was reverted");
        }

        if (isActiveSetAutomaticllyAddedNewAccount) {
            List<String> nameOfItemsToClicks = Arrays.asList(AUTOMATICLLY_ADDED_NEW_ACCOUNT, CURRENT_ACCOUNT);
            revertRightsForDisponent(harness, activeUserCredentials.getUsername(), nameOfItemsToClicks);
            harness.log("Rights to active disponent was reverted");
        }

        if (isPasiveSetRightsToMinimum && !isPasiveSetAutomaticllyAddedNewAccount) {
            List<String> nameOfItemsToClicks = Arrays.asList(AUTOMATICLLY_ADDED_NEW_ACCOUNT);
            revertRightsForDisponent(harness, pasiveUserCredentials.getUsername(), nameOfItemsToClicks);
            harness.log("Rights to pasive disponent was reverted");
        }
    }
}