package cz.moneta.test.harness.endpoints.smartbanka;

import cz.moneta.test.harness.connectors.mobile.AppiumMobileConnector;
import cz.moneta.test.harness.connectors.mobile.UnsupportedPlatformException;
import cz.moneta.test.harness.connectors.mobile.android.AndroidConnector;
import cz.moneta.test.harness.connectors.mobile.ios.IosConnector;
import cz.moneta.test.harness.context.StoreAccessor;
import cz.moneta.test.harness.endpoints.MobileEndpoint;
import org.openqa.selenium.By;

import java.util.Optional;

import static cz.moneta.test.harness.endpoints.smartbanka.MobilePlatform.getMobilePlatformFromConfig;

public class SbEndpoint extends MobileEndpoint<AppiumMobileConnector> {

    public SbEndpoint(StoreAccessor store) {
        super(() -> prepareConnector(store));
    }

    private static AppiumMobileConnector prepareConnector(StoreAccessor store) {
        MobilePlatform mobilePlatform = getMobilePlatformFromConfig(store, "mobile.platform");
        switch (mobilePlatform) {
            case ANDROID:
                return new AndroidConnector(By::id, store,
                        loadConfig(store, "appium.android.host"),
                        loadConfig(store, "appium.android.device"),
                        loadConfig(store, "appium.android.udid"),
                        loadConfig(store, "appium.android.package"),
                        loadConfig(store, "appium.android.path"));

            case IOS:
                return new IosConnector(
                        By::id,
                        store,
                        loadConfig(store, "appium.ios.host"),
                        loadConfig(store, "appium.ios.device"),
                        loadConfig(store, "appium.ios.udid"),
                        loadConfig(store, "appium.ios.bundleid"),
                        loadConfig(store, "appium.ios.path")
                );

            case IOS_SIMULATOR:
                return new IosConnector(
                        By::id,
                        store,
                        loadConfig(store, "appium.ios.host"),
                        loadConfig(store, "appium.ios.device"),
                        null,
                        loadConfig(store, "appium.ios.bundleid"),
                        loadConfig(store, "appium.ios.path")
                );

            default:
                throw new UnsupportedPlatformException("This platform is unsupported");
        }
    }

    private static String loadConfig(StoreAccessor store, String configKey) {
        return Optional.ofNullable(store.getConfig(configKey))
                .orElseThrow(() -> new IllegalStateException("You need to configure " + configKey + " to work with mobile device"));
    }

    public void connect() {
        this.connector.get();
    }

}
