/*
 * 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.cr.services.infrastructure.persistence.certificate;

import javax.decorator.Decorator;
import javax.decorator.Delegate;
import javax.inject.Inject;

import com.scytl.products.oscore.logging.api.domain.Level;
import com.scytl.products.oscore.logging.api.domain.LogContent;
import com.scytl.products.oscore.logging.api.writer.SecureLoggingWriter;
import com.scytl.products.ov.commons.beans.exceptions.DuplicateEntryException;
import com.scytl.products.ov.commons.tracking.TrackIdInstance;
import com.scytl.products.ov.cr.services.domain.model.certificate.CertificateEntity;
import com.scytl.products.ov.cr.services.domain.model.certificate.CertificateRepository;
import com.scytl.products.ov.cr.services.infrastructure.log.CertificateRegistryLogConstants;
import com.scytl.products.ov.cr.services.infrastructure.log.CertificateRegistryLogEvents;

/**
 * Decorator for CertificateRepository that adds secure logging
 */
@Decorator
public abstract class CertificateRepositoryDecorator implements CertificateRepository {

    @Inject
    @Delegate
    private CertificateRepository certificateRepository;

    @Inject
    private TrackIdInstance trackId;

    @Inject
    private SecureLoggingWriter secureLoggingWriter;


    @Override
    public CertificateEntity save(final CertificateEntity entity) throws DuplicateEntryException {
        try {
            final CertificateEntity certificateEntity = certificateRepository.save(entity);
            secureLoggingWriter.log(Level.INFO, new LogContent.LogContentBuilder()
                .logEvent(CertificateRegistryLogEvents.CERTIFICATE_SAVED)
                .objectId(entity.getCertificateName()).user("admin").electionEvent(entity.getElectionEventId())
                .additionalInfo(CertificateRegistryLogConstants.INFO_TRACK_ID, trackId.getTrackId())
                .createLogInfo());
            return certificateEntity;
        } catch (DuplicateEntryException ex) {
            secureLoggingWriter.log(Level.ERROR, new LogContent.LogContentBuilder()
                .logEvent(CertificateRegistryLogEvents.ERROR_SAVING_CERTIFICATE)
                .objectId(entity.getCertificateName()).user("admin").electionEvent(entity.getElectionEventId())
                .additionalInfo(CertificateRegistryLogConstants.INFO_TRACK_ID, trackId.getTrackId())
                .additionalInfo(CertificateRegistryLogConstants.INFO_ERR_DESC, ex.getMessage())
                .createLogInfo());
            throw ex;
        }
    }
}
