package com.atlassian.bitbucket.internal.branch.model.configuration.rest;

import com.atlassian.bitbucket.internal.branch.model.configuration.BranchTypeConfiguration;
import com.atlassian.bitbucket.internal.branch.model.rest.RestBranchType;
import com.atlassian.bitbucket.rest.RestMapEntity;
import com.atlassian.bitbucket.rest.annotation.JsonSurrogate;
import com.google.common.base.Function;
import org.codehaus.jackson.map.annotate.JsonSerialize;

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


@JsonSerialize
@JsonSurrogate(BranchTypeConfiguration.class)
public class RestBranchTypeConfiguration extends RestMapEntity {

    public static final String ID = RestBranchType.ID;
    public static final String DISPLAY_NAME = RestBranchType.DISPLAY_NAME;
    public static final String PREFIX = RestBranchType.PREFIX;
    public static final String ENABLED = "enabled";

    public static final Function<Object, RestBranchTypeConfiguration> REST_TRANSFORM =
            new Function<Object, RestBranchTypeConfiguration>() {
                @Override
                public RestBranchTypeConfiguration apply(Object input) {
                    return RestBranchTypeConfiguration.valueOf(input);
                }
            };


    @SuppressWarnings("unused") //Required for Jersey
    public RestBranchTypeConfiguration() {
    }

    public RestBranchTypeConfiguration(@Nonnull BranchTypeConfiguration configuration) {
        this(configuration.getId(), configuration.getDisplayName(), configuration.isEnabled(), configuration.getPrefix());
    }

    private RestBranchTypeConfiguration(@Nonnull String id, @Nonnull String displayName, boolean enabled, @Nullable String prefix) {
        put(ID, id);
        put(DISPLAY_NAME, displayName);
        put(ENABLED, enabled);
        putIfNotNull(PREFIX, prefix);
    }

    private RestBranchTypeConfiguration(Map<String, Object> values) {
        super(values);
    }

    @Nullable
    @SuppressWarnings("unchecked")
    public static RestBranchTypeConfiguration valueOf(@Nullable Object value) {
        if (value instanceof RestBranchTypeConfiguration) {
            return (RestBranchTypeConfiguration) value;
        } else if (value instanceof BranchTypeConfiguration) {
            return new RestBranchTypeConfiguration((BranchTypeConfiguration) value);
        } else if (value instanceof Map) {
            return new RestBranchTypeConfiguration((Map<String, Object>) value);
        }
        return null;
    }

    public String getId() {
        return getStringProperty(ID);
    }

    public String getPrefix() {
        return getStringProperty(PREFIX);
    }

    public boolean isEnabled() {
        return getBoolProperty(ENABLED);
    }
}


