package com.atlassian.stash.internal.web.repos;

import com.atlassian.bitbucket.content.ContentTreeNode;
import com.atlassian.bitbucket.content.Submodule;
import org.apache.commons.lang3.StringUtils;

import javax.annotation.Nonnull;

import static com.atlassian.bitbucket.content.ContentTreeNode.Type.DIRECTORY;
import static java.util.Objects.requireNonNull;

@SuppressWarnings("unused") //Methods are used via Reflection from Soy
public class ViewFile implements Comparable<ViewFile> {

    private final String browseUrl;
    private final String collapsedParents;
    private final String contentId;
    private final String name;
    private final String repositoryUrl;
    private final ContentTreeNode.Type type;
    private final String url;

    public ViewFile(ContentTreeNode node, String url) {
        this(requireNonNull(node, "node"), url, null, null);
    }

    public ViewFile(Submodule submodule) {
        this(requireNonNull(submodule, "submodule"), submodule.getUrl(),
                submodule.getBrowseUrl(), submodule.getRepositoryUrl());
    }

    private ViewFile(ContentTreeNode node, String url, String browseUrl, String repositoryUrl) {
        this.browseUrl = browseUrl;
        this.repositoryUrl = repositoryUrl;
        this.url = requireNonNull(url, "url");

        String parentPath = StringUtils.defaultString(node.getPath().getParent());

        collapsedParents = parentPath.isEmpty() ? "" : StringUtils.appendIfMissing(parentPath, "/");
        contentId = node.getContentId();
        name = node.getPath().getName();
        type = node.getType();
    }

    public String getCollapsedParents() {
        return collapsedParents;
    }

    public String getName() {
        return this.name;
    }

    public String getUrl() {
        return this.url;
    }

    public String getRepositoryUrl() {
        return this.repositoryUrl;
    }

    public String getBrowseUrl() {
        return this.browseUrl;
    }

    public String getContentId() {
        return this.contentId;
    }

    public ContentTreeNode.Type getType() {
        return this.type;
    }

    public ContentTreeNode.Type getTypeValue() {
        return this.type;
    }

    @Override
    public int compareTo(@Nonnull ViewFile o) {
        // If you change this logic please update the corresponding logic in file-table.js
        if (getTypeValue() == DIRECTORY ^ o.getTypeValue() == DIRECTORY) {
            return getTypeValue() == DIRECTORY ? -1 : 1;
        }

        int i = getName().compareToIgnoreCase(o.getName());
        return i == 0 ? getName().compareTo(o.getName()) : i;
    }
}
