/*
 * 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.AuthenticationContentEntity;
import com.scytl.products.ov.au.services.domain.model.authentication.AuthenticationContentRepository;
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 content repository decorator.
 */
@Decorator
public abstract class AuthenticationContentRepositoryDecorator implements AuthenticationContentRepository {

	@Inject
	@Delegate
	private AuthenticationContentRepository authenticationContentRepository;

	@Inject
	private TrackIdInstance trackId;

	@Inject
	private SecureLoggingWriter secureLoggingWriter;

	@Override
	public AuthenticationContentEntity save(final AuthenticationContentEntity entity) throws DuplicateEntryException {
		try {
            final AuthenticationContentEntity contentEntity = authenticationContentRepository.save(entity);
            secureLoggingWriter.log(Level.INFO,
                new LogContent.LogContentBuilder().logEvent(AuthenticationLogEvents.AUTH_CONTENT_SAVED)
                    .objectId("authContent").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_CONTENT)
                    .objectId("authContent").user("admin")
                    .electionEvent(entity.getElectionEventId())
                    .additionalInfo(AuthenticationLogConstants.INFO_TRACK_ID, trackId.getTrackId())
                    .additionalInfo(AuthenticationLogConstants.INFO_ERR_DESC, ex.getMessage())
                    .createLogInfo());
            throw ex;
		}
	}
}
