package com.atlassian.bitbucket.mesh.git;

import com.atlassian.bitbucket.mesh.repository.RepositoryManager;

import javax.annotation.Nonnull;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

import static java.util.Objects.requireNonNull;

public class DefaultRpcArgumentDecoder implements RpcArgumentDecoder {

    private static final Pattern PATTERN_REPOSITORY = Pattern.compile("\\$repository_path\\('(.+)'\\)");

    private final RepositoryManager repositoryManager;

    public DefaultRpcArgumentDecoder(RepositoryManager repositoryManager) {
        this.repositoryManager = repositoryManager;
    }

    @Nonnull
    @Override
    public List<String> decode(@Nonnull List<String> arguments) {
        requireNonNull(arguments, "arguments");

        return arguments.stream()
                .map(this::decode)
                .collect(Collectors.toList());
    }

    private String decode(String argument) {
        Matcher matcher = PATTERN_REPOSITORY.matcher(argument);
        if (matcher.matches()) {
            //Convert the repository ID to something Mesh can use.
            String id = matcher.group(1);
            return repositoryManager.getById(id).getPath().toString();
        }
        return argument;
    }
}
