package com.atlassian.bitbucket.internal.webhook.json;

import com.atlassian.bitbucket.internal.webhook.WebHookFilterParameters;
import com.atlassian.bitbucket.rest.RestMapEntity;
import com.atlassian.bitbucket.rest.annotation.JsonSurrogate;

import java.util.Map;
import java.util.Optional;

import static java.util.Optional.empty;
import static java.util.Optional.of;
import static java.util.Optional.ofNullable;

@JsonSurrogate(WebHookFilterParameters.class)
public class JsonWebHookFilterParameters extends RestMapEntity implements WebHookFilterParameters {

    private static final String PROP_PROJECT_ID = "projectId";
    private static final String PROP_REPOSITORY_ID = "repositoryId";

    public JsonWebHookFilterParameters(Map<String, ?> values) {
        super(values);
    }

    public JsonWebHookFilterParameters(WebHookFilterParameters parameters) {
        parameters.getProjectId().ifPresent(id -> put(PROP_PROJECT_ID, id));
        parameters.getRepositoryId().ifPresent(id -> put(PROP_REPOSITORY_ID, id));
    }

    @Override
    public Optional<Integer> getProjectId() {
        return containsKey(PROP_PROJECT_ID) ? of(getIntProperty(PROP_PROJECT_ID)) : empty();
    }

    @Override
    public Optional<Integer> getRepositoryId() {
        return containsKey(PROP_REPOSITORY_ID) ? ofNullable(getIntProperty(PROP_REPOSITORY_ID)) : empty();
    }

    public static WebHookFilterParameters valueOf(Object value) {
        if (value instanceof WebHookFilterParameters) {
            return (WebHookFilterParameters) value;
        }

        if (value instanceof Map) {
            return new JsonWebHookFilterParameters((Map<String, ?>) value);
        }

        return null;
    }
}
