package com.atlassian.bitbucket.mesh.repository;

import com.atlassian.bitbucket.mesh.git.AbstractParameters;
import com.atlassian.bitbucket.mesh.rpc.v1.RpcCreateRepositoryRequest;
import com.google.common.collect.ImmutableMap;
import com.google.protobuf.ByteString;

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

import static java.util.Objects.requireNonNull;

public class CreateRepositoryParameters extends AbstractParameters {

    private final String defaultBranch;
    private final String id;
    private final Map<String, String> metadata;
    private final Repository origin;

    private CreateRepositoryParameters(Builder builder) {
        super(builder);

        defaultBranch = builder.defaultBranch;
        id = builder.id;
        metadata = builder.metadata.build();
        origin = builder.origin;
    }

    @Nullable
    public String getDefaultBranch() {
        return defaultBranch;
    }

    @Nonnull
    public String getId() {
        return id;
    }

    @Nonnull
    public Map<String, String> getMetadata() {
        return metadata;
    }

    @Nullable
    public Repository getOrigin() {
        return origin;
    }

    @Nonnull
    public RpcCreateRepositoryRequest toCreateRepositoryRequest() {
        RpcCreateRepositoryRequest.Builder builder = RpcCreateRepositoryRequest.newBuilder()
                .putAllMetadata(metadata)
                .setRepository(id);
        if (origin != null) {
            builder.setOrigin(origin.getId());
        }
        if (defaultBranch != null) {
            builder.setDefaultBranch(ByteString.copyFromUtf8(defaultBranch));
        }
        return builder.build();
    }

    public static class Builder extends AbstractBuilder<Builder, CreateRepositoryParameters> {

        private final String id;
        private final ImmutableMap.Builder<String, String> metadata;

        private String defaultBranch;
        private Repository origin;

        public Builder(@Nonnull String id) {
            this.id = requireNonNull(id, "id");

            metadata = ImmutableMap.builder();
        }

        @Nonnull
        public CreateRepositoryParameters build() {
            return new CreateRepositoryParameters(this);
        }

        @Nonnull
        public Builder defaultBranch(@Nullable String value) {
            defaultBranch = value;
            return this;
        }

        @Nonnull
        public Builder metadata(@Nonnull Map<String, String> values) {
            metadata.putAll(requireNonNull(values, "metadata"));
            return this;
        }

        @Nonnull
        public Builder origin(@Nonnull Repository value) {
            origin = requireNonNull(value, "origin");
            return this;
        }

        @Nonnull
        @Override
        protected Builder self() {
            return this;
        }
    }
}
