package com.atlassian.stash.internal.scm.protocol.http;

import com.atlassian.bitbucket.i18n.I18nService;
import com.atlassian.bitbucket.scm.ScmRequest;
import com.atlassian.bitbucket.scm.ScmRequestCheck;
import com.atlassian.bitbucket.scm.http.HttpScmRequest;
import com.atlassian.bitbucket.server.ApplicationPropertiesService;
import org.springframework.beans.factory.annotation.Autowired;

import javax.annotation.Nonnull;
import java.io.IOException;

/**
 * Checks where SCM access is enabled over HTTP(S).
 *
 * @since 3.10
 */
public class HttpScmHostingCheck implements ScmRequestCheck {

    private final ApplicationPropertiesService applicationPropertiesService;
    private final I18nService i18nService;

    @Autowired
    public HttpScmHostingCheck(ApplicationPropertiesService applicationPropertiesService, I18nService i18nService) {
        this.applicationPropertiesService = applicationPropertiesService;
        this.i18nService = i18nService;
    }

    @Override
    public boolean check(@Nonnull ScmRequest request) throws IOException {
        if (request instanceof HttpScmRequest && !applicationPropertiesService.isHttpScmHostingEnabled()) {
            request.sendError(
                    i18nService.getMessage("bitbucket.scm.http.disabled"),
                    i18nService.getMessage("bitbucket.scm.http.disabled.detail")
            );
            return false;
        }

        return true;
    }

}
