package ru.yandex.webmaster3.storage.user.message;

import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import com.fasterxml.jackson.databind.ser.std.ToStringSerializer;

import java.math.BigInteger;
import java.util.UUID;

/**
 * @author avhaliullin
 */
@JsonSerialize(using = ToStringSerializer.class)
public class MessageId {
    private final UUID eventUuid;
    private final long hash;

    public MessageId(UUID eventUuid, long hash) {
        this.eventUuid = eventUuid;
        this.hash = hash;
    }

    public UUID getEventUuid() {
        return eventUuid;
    }

    public long getHash() {
        return hash;
    }

    public String toString() {
        return String.format("%s-%016x", eventUuid.toString(), hash);
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;

        MessageId messageId = (MessageId) o;

        if (hash != messageId.hash) return false;
        return eventUuid.equals(messageId.eventUuid);
    }

    @Override
    public int hashCode() {
        int result = eventUuid.hashCode();
        result = 31 * result + (int) (hash ^ (hash >>> 32));
        return result;
    }

    public static MessageId fromString(String s) {
        if (s == null) {
            return null;
        }
        int uuidEnd = s.lastIndexOf('-');
        if (uuidEnd < 0) {
            throw new IllegalArgumentException("String '" + s + "' is not valid message id");
        }
        try {
            UUID uuid = UUID.fromString(s.substring(0, uuidEnd));
            long hash = new BigInteger(s.substring(uuidEnd + 1), 16).longValue();
            return new MessageId(uuid, hash);
        } catch (IllegalArgumentException e) {
            throw new IllegalArgumentException("String '" + s + "' is not valid message id", e);
        }
    }
}
