package com.atlassian.bitbucket.internal.mirroring.mirror.jwt;

import com.atlassian.bitbucket.rest.RestMapEntity;

import javax.annotation.Nonnull;
import java.util.Date;
import java.util.Map;
import java.util.Optional;

import static java.util.Optional.empty;
import static java.util.Optional.ofNullable;

public class JwtClaims extends RestMapEntity {

    private static final String CONTEXT = "context";
    private static final String EXPIRATION_DATE = "exp";
    private static final String ISSUER = "iss";
    private static final String ISSUE_DATE = "iat";
    private static final String REPOSITORY = "repo";
    private static final String SUBJECT = "sub";
    private static final String USER = "user";

    @Nonnull
    public Optional<JwtContextUser> getContextUser() {
        //noinspection unchecked
        Map<String, Object> context = (Map<String, Object>) get(CONTEXT);
        if (context == null) {
            return empty();
        }
        return JwtContextUser.valueOf(context.get(USER));
    }

    @Nonnull
    public Date getExpiresDate() {
        return new Date(getLongProperty(EXPIRATION_DATE));
    }

    @Nonnull
    public String getIssuer() {
        return getStringProperty(ISSUER);
    }

    @Nonnull
    public Date getIsuedDate() {
        return new Date(getLongProperty(ISSUE_DATE));
    }

    @Nonnull
    public Optional<Integer> getRepository() {
        return Optional.of(getIntProperty(REPOSITORY));
    }

    @Nonnull
    public Optional<String> getSubject() {
        return ofNullable(getStringProperty(SUBJECT));
    }
}
