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

import com.atlassian.bitbucket.internal.importer.ExternalRepository;
import com.atlassian.bitbucket.rest.RestMapEntity;

import javax.annotation.Nullable;
import javax.validation.constraints.NotNull;
import java.util.Collection;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;

import static java.util.Optional.empty;

public class BitbucketCloudRepository extends RestMapEntity implements ExternalRepository {

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

    @NotNull
    @Override
    public String getCloneUrl() {
        Optional<String> cloneLink = empty();
        Map<String, ?> links = (Map<String, ?>) get("links");
        if (links != null) {
            Collection<Map<String, ?>> cloneLinks = (Collection<Map<String, ?>>) links.get("clone");
            if (cloneLinks != null) {
                cloneLink = cloneLinks.stream()
                        .filter(link -> link.get("name").equals("https"))
                        .map(link -> Objects.toString(link.get("href")))
                        .findFirst();
            }
        }
        return cloneLink.orElse(null);
    }

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

    @NotNull
    @Override
    public String getName() {
        return getStringProperty("name");
    }

    @NotNull
    @Override
    public String getScmId() {
        return getStringProperty("scm");
    }
}
