package com.atlassian.stash.internal.rest.pull;

import com.atlassian.bitbucket.pull.PullRequestDirection;
import com.atlassian.bitbucket.rest.RestResource;
import com.atlassian.bitbucket.rest.BadRequestException;
import com.atlassian.bitbucket.i18n.I18nService;
import com.atlassian.bitbucket.pull.PullRequestService;
import org.apache.commons.lang3.StringUtils;

import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import java.util.List;
import java.util.Locale;

import static com.atlassian.bitbucket.util.MoreCollectors.toImmutableList;
import static java.util.Arrays.stream;

public abstract class AbstractPullRequestResource extends RestResource {

    protected final PullRequestService pullRequestService;

    protected AbstractPullRequestResource(I18nService i18nService, PullRequestService pullRequestService) {
        super(i18nService);
        this.pullRequestService = pullRequestService;
    }

    @Nonnull
    protected <T> T ensureHasProperty(@Nonnull String propertyName, @Nullable T value) {
        if (value == null) {
            throw new BadRequestException(i18nService.getMessage("bitbucket.rest.pullrequests.property.notsupplied", propertyName));
        }

        return value;
    }

    protected void ensurePropertySupplied(@Nonnull String fieldName, boolean supplied) {
        if (!supplied) {
            throw new BadRequestException(i18nService.getMessage("bitbucket.rest.pullrequests.property.notsupplied", fieldName));
        }
    }

    protected void ensurePropertyNotSupplied(@Nonnull String fieldName, boolean supplied) {
        if (supplied) {
            throw new BadRequestException(i18nService.getMessage("bitbucket.rest.pullrequests.property.supplied", fieldName));
        }
    }

    @Nonnull
    protected PullRequestDirection toDirection(@Nonnull String direction) {
        try {
            return StringUtils.isEmpty(direction) ? PullRequestDirection.INCOMING : PullRequestDirection.valueOf(direction.toUpperCase(Locale.ROOT));
        } catch (IllegalArgumentException e) {
            throw new BadRequestException(
                    i18nService.getMessage("bitbucket.rest.pullrequests.direction.invalid",
                            toLowercaseNames(PullRequestDirection.values())));
        }
    }

    @Nonnull
    protected List<String> toLowercaseNames(@Nonnull Enum[] values) {
        return stream(values)
                .map(value -> value.name().toLowerCase(Locale.ROOT))
                .collect(toImmutableList());
    }
}
