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

import com.atlassian.bitbucket.build.BuildState;
import com.atlassian.bitbucket.build.BuildStatus;
import com.atlassian.bitbucket.rest.RestMapEntity;
import com.atlassian.bitbucket.rest.util.RestPage;
import com.atlassian.bitbucket.rest.util.RestDocUtils;
import org.codehaus.jackson.map.annotate.JsonSerialize;

import java.util.Date;
import java.util.function.Function;

@JsonSerialize
public class RestBuildStatus extends RestMapEntity {

    public static final Function<BuildStatus, RestBuildStatus> REST_TRANSFORM = RestBuildStatus::new;

    private static final String DATE_ADDED = "dateAdded";
    private static final String DESCRIPTION = "description";
    private static final String KEY = "key";
    private static final String NAME = "name";
    private static final String STATE = "state";
    private static final String URL = "url";

    @SuppressWarnings("unused") // required by Jersey since the user can submit statuses via the POST endpoint
    public RestBuildStatus() {
    }

    protected RestBuildStatus(BuildStatus buildStatus) {
        this(buildStatus.getState(), buildStatus.getKey(), buildStatus.getName(), buildStatus.getUrl(),
                buildStatus.getDescription(), buildStatus.getDateAdded());
    }

    protected RestBuildStatus(BuildState state, String key, String name, String url, String description, Date dateAdded) {
        put(STATE, state);
        put(KEY, key);
        put(NAME, name);
        put(URL, url);
        put(DESCRIPTION, description);
        if (dateAdded != null) {
            put(DATE_ADDED, dateAdded.getTime());
        }
    }

    public long getDateAdded() {
        return getLongProperty(DATE_ADDED);
    }

    public String getDescription() {
        return getStringProperty(DESCRIPTION);
    }

    public String getKey() {
        return getStringProperty(KEY);
    }

    public String getName() {
        return getStringProperty(NAME);
    }

    public BuildState getState() {
        return getEnumProperty(STATE, BuildState.class);
    }

    public String getUrl() {
        return getStringProperty(URL);
    }

    // REST Documentation Examples

    public static final RestBuildStatus EXAMPLE
            = new RestBuildStatus(BuildState.SUCCESSFUL, "REPO-MASTER", "REPO-MASTER-42",
            "https://bamboo.example.com/browse/REPO-MASTER-42", "Changes by John Doe", new Date());

    public static final RestPage<RestBuildStatus> PAGE_EXAMPLE = RestDocUtils.pageOf(EXAMPLE);

}
