package com.atlassian.stash.internal.web.help;

import com.atlassian.plugin.servlet.DownloadableResource;
import com.atlassian.plugin.webresource.QueryParams;
import com.atlassian.plugin.webresource.transformer.*;
import com.atlassian.plugin.webresource.url.UrlBuilder;
import com.atlassian.bitbucket.help.HelpPathService;
import org.apache.commons.lang3.StringEscapeUtils;

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

public class JavascriptHelpUrlWebResourceTransformer implements WebResourceTransformerFactory,
        TransformerUrlBuilder, UrlReadingWebResourceTransformer {

    private static final Pattern PATTERN = Pattern.compile(
            "bitbucket_help_url" +
                    "\\(\\s*" +                  // start paren
                    "(['\"])([\\w.-]+)\\1" +     // single or double quoted key-style word
                    "\\s*\\)");                  // end paren

    private final HelpPathService helpPathService;

    public JavascriptHelpUrlWebResourceTransformer(HelpPathService helpPathService) {
        this.helpPathService = helpPathService;
    }

    @Override
    public TransformerUrlBuilder makeUrlBuilder(TransformerParameters parameters) {
        return this;
    }

    @Override
    public UrlReadingWebResourceTransformer makeResourceTransformer(TransformerParameters parameters) {
        return this;
    }

    @Override
    public void addToUrl(UrlBuilder urlBuilder) {
        // no-op, URLs are immutable and only depend on the build hash
    }

    @Override
    public DownloadableResource transform(TransformableResource transformableResource, QueryParams params) {
        return new CharSequenceDownloadableResource(transformableResource.nextResource()) {
            @Override
            protected CharSequence transform(CharSequence original) {
                return doTransform(original);
            }
        };
    }

    protected String doTransform(CharSequence originalContent) {
        Matcher matcher = PATTERN.matcher(originalContent);

        StringBuffer result = new StringBuffer();
        while (matcher.find()) {
            String helpPageUrl = helpPathService.getPageUrl(matcher.group(2));

            matcher.appendReplacement(result, "");
            result
                    .append("'")
                    .append(StringEscapeUtils.escapeEcmaScript(helpPageUrl == null ? "" : helpPageUrl))
                    .append("'");
        }
        matcher.appendTail(result);

        return result.toString();
    }
}
