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

import cz.moneta.test.harness.connectors.GreenScreenConnector;
import cz.moneta.test.harness.context.StoreAccessor;
import cz.moneta.test.harness.endpoints.Endpoint;
import cz.moneta.test.harness.support.auth.AuthSupport;
import cz.moneta.test.harness.support.auth.Credentials;
import cz.moneta.test.harness.support.greenscreen.Key;

import java.util.Optional;

public class GreenScreenEndpoint implements Endpoint {

    private final ThreadLocal<GreenScreenConnector> connector = ThreadLocal.withInitial(this::initConnector);
    private StoreAccessor store;

    public GreenScreenEndpoint(StoreAccessor store) {
        this.store = store;
    }

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

    public String getText(int row, int column, int length) {
        return connector.get().getText(row, column, length);
    }

    public void pressKey(Key key) {
        connector.get().pressKey(key);
    }

    public void type(int row, int column, String text) {
        connector.get().type(row, column, text);
    }

    private GreenScreenConnector initConnector() {
        String endpointName = "endpoints.greenscreen.url";
        Credentials credentials = AuthSupport.getCredentials("greenscreen", store);
        return Optional.ofNullable(store.getConfig(endpointName))
                .map(url -> new GreenScreenConnector(url, credentials.getUsername(), credentials.getPassword()))
                .orElseThrow(() -> new IllegalStateException("You need to configure " + endpointName + " to work with Greenscreen interface"));
    }
}
