/*
 * 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.persistence;

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.au.services.domain.model.authentication.AuthenticationCerts;
import com.scytl.products.ov.au.services.domain.model.authentication.AuthenticationCertsRepository;
import com.scytl.products.ov.au.services.infrastructure.log.AuthenticationLogConstants;
import com.scytl.products.ov.au.services.infrastructure.log.AuthenticationLogEvents;
import com.scytl.products.ov.commons.beans.exceptions.DuplicateEntryException;
import com.scytl.products.ov.commons.tracking.TrackIdInstance;

/**
 * Authentication certs repository decorator.
 */
@Decorator
public abstract class AuthenticationCertsRepositoryDecorator implements AuthenticationCertsRepository {

	@Inject
	@Delegate
	private AuthenticationCertsRepository authenticationCertsRepository;

	@Inject
	private TrackIdInstance trackId;

	@Inject
	private SecureLoggingWriter secureLoggingWriter;

	@Override
	public AuthenticationCerts save(final AuthenticationCerts entity) throws DuplicateEntryException {
		try {
            final AuthenticationCerts contentEntity = authenticationCertsRepository.save(entity);
            secureLoggingWriter.log(Level.INFO,
                new LogContent.LogContentBuilder().logEvent(AuthenticationLogEvents.AUTH_CERTS_SAVED)
                    .objectId("authCerts").user("admin")
                    .electionEvent(entity.getElectionEventId())
                    .additionalInfo(AuthenticationLogConstants.INFO_TRACK_ID, trackId.getTrackId())
					.createLogInfo());
            return contentEntity;
        } catch (DuplicateEntryException ex) {
            secureLoggingWriter.log(Level.ERROR,
                new LogContent.LogContentBuilder().logEvent(AuthenticationLogEvents.ERROR_SAVING_AUTH_CERTS)
                    .objectId("authContent").user("admin")
                    .electionEvent(entity.getElectionEventId())
                    .additionalInfo(AuthenticationLogConstants.INFO_TRACK_ID, trackId.getTrackId())
                    .additionalInfo(AuthenticationLogConstants.INFO_ERR_DESC, ex.getMessage())
                    .createLogInfo());
            throw ex;
		}
	}
}
