package com.atlassian.bitbucket.mesh.repository;

import io.netty.handler.codec.http.QueryStringDecoder;

import javax.annotation.Nonnull;
import java.nio.file.Path;
import java.util.List;
import java.util.Map;

import static java.util.Objects.requireNonNull;

public abstract class AbstractRepository implements Repository {

    RepositoryAttributeManager attributeManager;

    private Map<String, List<String>> parameters;

    @Override
    public String getParameter(@Nonnull String name) {
        if (parameters == null) {
            parameters = new QueryStringDecoder(getId()).parameters();
        }
        List<String> values = parameters.get(requireNonNull(name, "name"));
        return values == null || values.isEmpty() ? null : values.get(values.size() - 1);
    }

    @Override
    public boolean isReadOnly() {
        return attributeManager != null && attributeManager.isReadOnly(getId());
    }

    @Override
    public void setReadOnly(boolean value) {
        checkAttributesAttached();

        attributeManager.setReadOnly(getId(), value);
    }

    void attachAttributes(@Nonnull RepositoryAttributeManager attributeManager) {
        this.attributeManager = requireNonNull(attributeManager, "attributeManager");
    }

    void checkAttributesAttached() {
        if (attributeManager == null) {
            throw new IllegalStateException("Attributes are not attached");
        }
    }

    @Nonnull
    abstract Path getTemplateDir();
}
