package com.atlassian.bitbucket.internal.importer.rest;

import com.atlassian.bitbucket.internal.importer.ExternalRepository;
import com.atlassian.bitbucket.rest.RestMapEntity;
import com.atlassian.bitbucket.rest.annotation.JsonSurrogate;
import org.codehaus.jackson.map.annotate.JsonSerialize;

import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import javax.validation.constraints.NotNull;
import java.util.Map;

@JsonSerialize
@JsonSurrogate(ExternalRepository.class)
public class RestExternalRepository extends RestMapEntity implements ExternalRepository {

    public static final String CLONE_URL = "cloneUrl";
    public static final String DESCRIPTION = "description";
    public static final String NAME = "name";
    public static final String SCM_ID = "scmId";

    public RestExternalRepository(Map map) {
        putAll(map);
    }

    public RestExternalRepository(ExternalRepository externalRepository) {
        put(CLONE_URL, externalRepository.getCloneUrl());
        put(DESCRIPTION, externalRepository.getDescription());
        put(NAME, externalRepository.getName());
        put(SCM_ID, externalRepository.getScmId());
    }

    @Nonnull
    @NotNull
    @Override
    public String getCloneUrl() {
        return getStringProperty(CLONE_URL);
    }

    @Nullable
    @Override
    public String getDescription() {
        return getStringProperty(DESCRIPTION);
    }

    @Nonnull
    @NotNull
    @Override
    public String getName() {
        return getStringProperty(NAME);
    }

    @Nonnull
    @NotNull
    @Override
    public String getScmId() {
        return getStringProperty(SCM_ID);
    }

    @Nullable
    @SuppressWarnings("unchecked")
    public static ExternalRepository valueOf(@Nullable Object value) {
        if (value instanceof RestExternalRepository) {
            return (RestExternalRepository) value;
        }
        if (value instanceof Map) {
            return new RestExternalRepository((Map) value);
        }

        return null;
    }
}
