package cz.moneta.test.dsl.oauth2.web;

import cz.moneta.test.harness.context.StoreAccessor;
import cz.moneta.test.harness.endpoints.oauth2.web.Oauth2WebEndpoint;
import cz.moneta.test.harness.exception.HarnessException;
import cz.moneta.test.harness.support.web.CustomAction;
import cz.moneta.test.harness.support.web.Wait;
import cz.moneta.test.harness.support.web.WebFlow;

import static cz.moneta.test.dsl.oauth2.web.ThirdPartyApplicationPageWithToken.BODY_TAG;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Wait(value = BODY_TAG)
public interface ThirdPartyApplicationPageWithToken extends WebFlow<ThirdPartyApplicationPageWithToken>, StoreAccessor {
    String AUTH_CODE_STORE = "AUTH_CODE";
    String BODY_TAG = "//body[contains(.,'gemwebdevx')]";
    Pattern CODE_PATTERN_PSD2 = Pattern.compile(".*code=(.*)");
    Pattern CODE_PATTERN_KYC = Pattern.compile(".*code=(.*)&state.*");

    @CustomAction
    default ThirdPartyApplicationPageWithToken getAuthTokenAndStoreIt() {
        Oauth2WebEndpoint endpoint = getEndpoint(Oauth2WebEndpoint.class);
        Matcher m = CODE_PATTERN_PSD2.matcher(endpoint.getCurrentUrl());
        if (m.matches()) {
            String token = m.group(1);
            store(AUTH_CODE_STORE, token);
            log("Auth code is: {}", token);
        } else {
            throw new HarnessException("Error getting parameter Auth code from URL");
        }
        return null;
    }

    @CustomAction
    default ThirdPartyApplicationPageWithToken getAuthTokenAndStoreItKyc() {
        Oauth2WebEndpoint endpoint = getEndpoint(Oauth2WebEndpoint.class);
        Matcher m = CODE_PATTERN_KYC.matcher(endpoint.getCurrentUrl());
        if (m.matches()) {
            String token = m.group(1);
            store(AUTH_CODE_STORE, token);
            log("Auth code is: {}", token);
        } else {
            throw new HarnessException("Error getting parameter Auth code from URL");
        }
        return null;
    }
}