package cz.moneta.test.dsl.ib.settings.smartbanka;

import cz.moneta.test.dsl.ib.IbPageFlow;
import cz.moneta.test.dsl.ib.components.MainMenu;
import cz.moneta.test.dsl.ib.settings.ib.SettingsVerticalMenu;
import cz.moneta.test.harness.context.StoreAccessor;
import cz.moneta.test.harness.endpoints.ib.IbEndpoint;
import cz.moneta.test.harness.endpoints.smartbanka.MobilePlatform;
import cz.moneta.test.harness.support.util.Level;
import cz.moneta.test.harness.support.web.Click;
import cz.moneta.test.harness.support.web.CustomAction;
import cz.moneta.test.harness.support.web.Lookup;
import cz.moneta.test.harness.support.web.Wait;

import static cz.moneta.test.dsl.ib.settings.smartbanka.SmartBankingPage.TITLE_TEXT;

@Wait(TITLE_TEXT)
public interface SmartBankingPage extends IbPageFlow<SmartBankingPage>, MainMenu, SettingsVerticalMenu {
    String TITLE_TEXT = "//h3[text() = 'Správa registrovaných mobilních zařízení']";
    String REGISTER_LINK = "//img[@alt='Registrace zařízení']";
    String UNREGISTER_LINK = "//img[@alt='Odstranit']";

    String DEVICES_LIST = "//table[contains(@id, 'smartBankList')]/tbody[count(tr[contains(@id, 'a')]) = 3]";
    String DEVICE = "//td[contains(text(), '%s')]//..//input[@id='productIdRadio']";

    @Click(UNREGISTER_LINK)
    DeviceRemovalWizard startDeviceRemoval();

    @Click(REGISTER_LINK)
    DeviceRegistrationWizard startDeviceRegistration();

    @CustomAction
    default SmartBankingPage chooseDevice(StoreAccessor store){
        IbEndpoint endpoint = getEndpoint(IbEndpoint.class);
        String deviceName = store.getConfig("appium.android.device");
        if (!MobilePlatform.isAndroid(store)){
           deviceName = store.getConfig("appium.ios.device");
        }
        String path = String.format(DEVICE, deviceName);
        if (endpoint.isElementPresent(path, Lookup.XPATH)){
            endpoint.click(() -> path, Lookup.XPATH);
        }else {
            log(Level.INFO,"Mobile device " + deviceName + " was not found");
        }
        return null;
    }

    @CustomAction
    default DeviceRegistrationWizard startRegistration(StoreAccessor store, String mobileKey) {
        IbEndpoint ibEndpoint = getEndpoint(IbEndpoint.class);
        if (ibEndpoint.isElementVisible(5, DEVICES_LIST, Lookup.DEFAULT) &&
                !ibEndpoint.isElementVisible(10, REGISTER_LINK, Lookup.DEFAULT)) {
            return
                    chooseDevice(store)
                    .startDeviceRemoval()
                    .confirmRemovalIntent()
                    .typeSmsCode(mobileKey)
                    .validateMobileKey()
                    .onSettingsPage()
                    .selectSmartBanka()
                    .startDeviceRegistration();
        }
        return startDeviceRegistration();
    }
}
