package eu.dnetlib.uoaadmintoolslibrary.recaptcha;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Configurable;
import org.springframework.boot.web.client.RestTemplateBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.client.RestOperations;

import java.net.URI;
import java.util.regex.Pattern;

import eu.dnetlib.uoaadmintoolslibrary.configuration.properties.GoogleConfig;
import eu.dnetlib.uoaadmintoolslibrary.entities.email.GoogleResponse;
import eu.dnetlib.uoaadmintoolslibrary.handlers.InvalidReCaptchaException;

@Service
@Configurable
public class VerifyRecaptcha {
    private final Logger log = Logger.getLogger(this.getClass());
    @Autowired
    private RestOperations restTemplate;

    @Autowired
    private GoogleConfig googleConfig;

    private static Pattern RESPONSE_PATTERN = Pattern.compile("[A-Za-z0-9_-]+");

    @Bean
    public RestOperations restTemplate(RestTemplateBuilder builder) {
        return builder.build();
    }

    public void processResponse(String response) throws InvalidReCaptchaException {
        if(!responseSanityCheck(response)) {
            InvalidReCaptchaException e = new InvalidReCaptchaException("Response contains invalid characters");
            log.error("Response contains invalid characters", e);
            throw e;
        }

        URI verifyUri = URI.create(String.format(
                "https://www.google.com/recaptcha/api/siteverify?secret=%s&response=%s",
                googleConfig.getSecret(), response));

        GoogleResponse googleResponse = restTemplate.getForObject(verifyUri, GoogleResponse.class);

        if(!googleResponse.isSuccess()) {
            log.error("Has client error:"+googleResponse.hasClientError());
            InvalidReCaptchaException e = new InvalidReCaptchaException("reCaptcha was not successfully validated");
            log.error("reCaptcha was not successfully validated", e);
            throw e;
        }
    }

    private boolean responseSanityCheck(String response) {
        return StringUtils.hasLength(response) && RESPONSE_PATTERN.matcher(response).matches();
    }
}
