package com.atlassian.bitbucket.internal.integration.jira;

import com.atlassian.bitbucket.integration.jira.JiraIssue;

import javax.annotation.Nonnull;
import javax.annotation.Nullable;

import static com.google.common.base.Preconditions.*;

public class SimpleJiraIssue implements JiraIssue, Comparable<SimpleJiraIssue> {

    private final long issueNumber;
    private final String key;
    private final String projectKey;
    private final String url;

    public SimpleJiraIssue(String key, String url) {
        this.key = checkNotNull(key, "Issue key must not be null");
        this.url = checkNotNull(url, "Issue url must not be null");

        int offset = key.lastIndexOf("-");
        projectKey = key.substring(0, offset);
        issueNumber = Long.parseLong(key.substring(offset + 1));
    }

    @Nullable
    public static SimpleJiraIssue maybeCreate(String key, String url) {
        try {
            return new SimpleJiraIssue(key, url);
        } catch (IndexOutOfBoundsException | NumberFormatException e) {
            return null;
        }
    }

    @Override
    public int compareTo(@Nonnull SimpleJiraIssue o) {
        int i = projectKey.compareTo(o.projectKey);
        return i == 0 ? Long.compare(issueNumber, o.issueNumber) : i;
    }

    @Override
    public boolean equals(Object obj) {
        if (!(obj instanceof SimpleJiraIssue)) {
            return false;
        }

        return key.equals(((SimpleJiraIssue) obj).getKey());
    }

    @Nonnull
    @Override
    public String getKey() {
        return key;
    }

    @Nonnull
    @Override
    public String getUrl() {
        return url;
    }

    @Override
    public int hashCode() {
        return key.hashCode();
    }
}
