package com.atlassian.stash.internal.plugin.hooks.task;

import com.atlassian.bitbucket.i18n.I18nService;
import com.atlassian.bitbucket.repository.Repository;
import com.atlassian.bitbucket.rest.RestErrorMessage;
import com.atlassian.bitbucket.rest.fragment.RestFragment;
import com.atlassian.bitbucket.rest.fragment.RestFragmentContext;
import com.google.common.collect.ImmutableMap;

import javax.annotation.Nonnull;
import java.util.Map;
import java.util.Optional;

public class IncompleteTasksRestFragment implements RestFragment {

    private static final String INCOMPLETE_TASKS_KEY = "requiredAllTasksComplete";

    private final IncompleteTasksMergeCheckConfig config;
    private final I18nService i18nService;

    public IncompleteTasksRestFragment(IncompleteTasksMergeCheckConfig config, I18nService i18nService) {
        this.config = config;
        this.i18nService = i18nService;
    }

    @Nonnull
    @Override
    public Map<String, Object> execute(@Nonnull RestFragmentContext fragmentContext,
                                       @Nonnull Map<String, Object> requestContext) {
        Repository repository = (Repository) requestContext.get("repository");

        if (fragmentContext.getMethod().equals("GET")) {
            return doGet(repository);
        } else if (fragmentContext.getMethod().equals("POST")) {
            return doPost(fragmentContext, repository);
        }

        return ImmutableMap.of(INCOMPLETE_TASKS_KEY, i18nService.getMessage("bitbucket.pull.tasks.rest.method.unsupported",
                fragmentContext.getMethod()));
    }

    @Nonnull
    @Override
    public Map<String, Object> validate(@Nonnull RestFragmentContext fragmentContext,
                                        @Nonnull Map<String, Object> requestContext) {
        if (fragmentContext.getMethod().equals("POST")) {
            Optional<Object> property = fragmentContext.getBodyProperty(INCOMPLETE_TASKS_KEY);

            if (property.isPresent() && !(property.get() instanceof Boolean)) {
                return new RestErrorMessage(INCOMPLETE_TASKS_KEY,
                        i18nService.getMessage("bitbucket.pull.tasks.rest.invalid"));
            }
        }

        return ImmutableMap.of();
    }

    private Map<String, Object> doGet(Repository repository) {
        return ImmutableMap.of(INCOMPLETE_TASKS_KEY, config.isResolutionRequired(repository));
    }

    private Map<String, Object> doPost(RestFragmentContext fragmentContext, Repository repository) {
        fragmentContext.getBodyProperty(INCOMPLETE_TASKS_KEY).ifPresent(
                b -> config.setResolutionRequired(repository, (Boolean) b)
        );

        return doGet(repository);
    }
}