package com.atlassian.bitbucket.internal.mirroring.mirror.rest.cloud;

import com.atlassian.bitbucket.internal.mirroring.mirror.MinimalExternalRepository;
import com.atlassian.bitbucket.rest.RestMapEntity;

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

import static com.atlassian.bitbucket.internal.mirroring.mirror.rest.cloud.RestCloudEntityProperties.*;
import static java.util.Optional.ofNullable;

/**
 * Minimal external repository in BB Cloud where only id, name, scmId and slug are known.
 */
public class RestCloudMinimalExternalRepository extends RestMapEntity implements MinimalExternalRepository {

    public RestCloudMinimalExternalRepository() {
    }

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

    @Nonnull
    @Override
    public String getId() {
        return getStringProperty(UUID);
    }

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

    @Nonnull
    @Override
    public RestCloudExternalProject getProject() {
        // until project entities are returned from the production API's repo entity
        // we need to use the default project if it is absent
        return ofNullable(get(PROJECT))
                .flatMap(value -> ofNullable(RestCloudExternalProject.valueOf(value)))
                .orElseGet(RestCloudMinimalExternalRepository::newDefaultProject);
    }

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

    @Nonnull
    @Override
    public String getSlug() {
        String[] fullNameSegments = getStringProperty(FULL_NAME).split("/");
        return fullNameSegments[fullNameSegments.length - 1];
    }

    @Override
    public boolean isPublic() {
        return !getBoolProperty(IS_PRIVATE, true);
    }

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

    /**
     * TODO: remove when projects are return from the production API
     */
    @Nonnull
    private static RestCloudExternalProject newDefaultProject() {
        RestCloudExternalProject project = new RestCloudExternalProject();
        project.put(UUID, "{bitbucket-org}");
        project.put(IS_PRIVATE, true);
        project.put(KEY, "BITBUCKET");
        project.put(NAME, "bitbucket.org");
        return project;
    }
}
