/*
 * Copyright 2018 Scytl Secure Electronic Voting SA
 *
 * All rights reserved
 *
 * See our extended copyright notice in *file 'Copyright.txt' which is part of this source code package
 */
package com.scytl.products.ov.au.services.infrastructure.log;

import java.io.IOException;
import java.util.regex.Pattern;

import javax.inject.Inject;
import javax.json.JsonException;
import javax.json.JsonObject;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.scytl.cryptolib.api.exceptions.GeneralCryptoLibException;
import com.scytl.products.ov.au.services.domain.model.authentication.AuthenticationToken;
import com.scytl.products.ov.commons.logging.service.AuthTokenHashService;
import com.scytl.products.ov.commons.ui.ws.rs.ObjectMappers;
import com.scytl.products.ov.commons.util.JsonUtils;

/**
 * Helper methods for secure logging purposes.
 */
public class SecureLoggerHelper {
    private static final Pattern ID_PATTERN = Pattern.compile("[a-zA-Z0-9\\=]*");

    private static final Pattern TIMESTAMP_PATTERN = Pattern.compile("[0-9]*");

    @Inject
    private AuthTokenHashService authTokenHashService;

    private static final Logger LOG = LoggerFactory.getLogger("std");

    /**
     * Computes the hash of the auth token object.
     *
     * @param token the auth token.
     * @return the result of hashing the auth token.
     */
    public String getAuthTokenHash(final AuthenticationToken token) {
        String hash = "";
        if (token != null) {
            try {
                String json = ObjectMappers.toJson(token);
                JsonObject object = JsonUtils.getJsonObject(json);
                hash = authTokenHashService.hash(object);
            } catch (JsonException | IllegalStateException | IOException | GeneralCryptoLibException e) {
                LOG.error("Error creating hash of authentication token for secure logging", e);
            }
        }
        return hash;
    }

    /**
     * Returns sanitized identifier of a given authentication token.
     *
     * @param token the token
     * @return the identifier.
     */
    public String getAuthTokenId(final AuthenticationToken token) {
        return sanitize(token.getId(), ID_PATTERN);
    }

    /**
     * Returns sanitized timestamp of a given authentication token.
     *
     * @param token the token
     * @return the timestamp.
     */
    public String getAuthTokenTimestamp(final AuthenticationToken token) {
        return sanitize(token.getTimestamp(), TIMESTAMP_PATTERN);
    }

    private String sanitize(final String value, final Pattern pattern) {
        if (value == null) {
            return "";
        }
        if (!pattern.matcher(value).matches()) {
            return "Invalid";
        }
        return value;
    }
}
