package org.jabref.model.entry.identifier;

import java.net.URI;
import java.net.URISyntaxException;
import java.util.Objects;
import java.util.Optional;

import org.jabref.architecture.AllowedToUseLogic;
import org.jabref.logic.util.strings.StringUtil;
import org.jabref.model.entry.field.Field;
import org.jabref.model.entry.field.StandardField;

import org.jspecify.annotations.NonNull;

/// Article identifier for MathSciNet (also sometimes called "MRNumber")
@AllowedToUseLogic("Uses StringUtil temporarily")
public class MathSciNetId implements Identifier {

    private final String identifier;

    public MathSciNetId(@NonNull String identifier) {
        this.identifier = identifier;
    }

    public static Optional<MathSciNetId> parse(String mrNumberRaw) {
        // Take everything before whitespace or open bracket, so something like `619693 (82j:58046)` gets parsed correctly
        String identifier = StringUtil.tokenizeToList(mrNumberRaw, " (").getFirst().trim();
        return Optional.of(new MathSciNetId(identifier));
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) {
            return true;
        }
        if (o == null || getClass() != o.getClass()) {
            return false;
        }
        MathSciNetId that = (MathSciNetId) o;
        return Objects.equals(identifier, that.identifier);
    }

    @Override
    public int hashCode() {
        return Objects.hash(identifier);
    }

    @Override
    public String toString() {
        return identifier;
    }

    /// Get URL in online database.
    @Override
    public Optional<URI> getExternalURI() {
        try {
            return Optional.of(new URI("https://www.ams.org/mathscinet-getitem?mr=" + identifier));
        } catch (URISyntaxException e) {
            return Optional.empty();
        }
    }

    @Override
    public Field getDefaultField() {
        return StandardField.MR_NUMBER;
    }

    @Override
    public String asString() {
        return identifier;
    }
}
