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

import com.atlassian.bitbucket.util.UrlUtils;
import com.google.common.primitives.Ints;

import javax.annotation.Nullable;
import java.util.regex.MatchResult;
import java.util.regex.Pattern;

/**
 * URI for repository attachments. As these URIs are stored in comments, the format must be kept stable (or the comment
 * source migrated).
 */
public class AttachmentUri {

    /**
     * Pattern for finding attachment URIs inside text.
     */
    public static final Pattern PATTERN = Pattern.compile("attachment:(\\d+)/([\\w\\-.*_+%]+)");

    private final int repositoryId;
    private final String attachmentId;

    public AttachmentUri(int repositoryId, String attachmentId) {
        this.repositoryId = repositoryId;
        this.attachmentId = attachmentId;
    }

    /**
     * @param matchResult the match result as obtained by a match of {@link #PATTERN}
     * @return an AttachmentUri or {@code null}
     */
    @Nullable
    public static AttachmentUri from(MatchResult matchResult) {
        String repositoryIdString = matchResult.group(1);
        String encodedAttachmentId = matchResult.group(2);

        Integer repositoryId = Ints.tryParse(repositoryIdString);
        if (repositoryId == null) {
            return null;
        }

        String attachmentId = UrlUtils.decodeURL(encodedAttachmentId);

        return new AttachmentUri(repositoryId, attachmentId);
    }

    public int getRepositoryId() {
        return repositoryId;
    }

    public String getAttachmentId() {
        return attachmentId;
    }

    /**
     * @return the attachment URI in a format that can later be parsed again using {@link #PATTERN} and {@link #from}.
     */
    @Override
    public String toString() {
        String encodedAttachmentId = UrlUtils.encodeURL(attachmentId);
        return "attachment:" + repositoryId + "/" + encodedAttachmentId;
    }

}
