/*
 * 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.ei.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.commons.beans.exceptions.DuplicateEntryException;
import com.scytl.products.ov.commons.tracking.TrackIdInstance;
import com.scytl.products.ov.ei.services.domain.model.content.ElectionInformationContent;
import com.scytl.products.ov.ei.services.domain.model.content.ElectionInformationContentRepository;
import com.scytl.products.ov.ei.services.infrastructure.log.ElectionInformationLogConstants;
import com.scytl.products.ov.ei.services.infrastructure.log.ElectionInformationLogEvents;

/**
 * Decorator for the ballottext repository.
 */
@Decorator
public abstract class ElectionInformationContentRepositoryDecorator implements ElectionInformationContentRepository {

	@Inject
	@Delegate
	private ElectionInformationContentRepository electionInformationContentRepository;

	@Inject
	private TrackIdInstance trackId;

	@Inject
	private SecureLoggingWriter secureLoggerWriter;

	@Override
	public ElectionInformationContent save(final ElectionInformationContent entity) throws DuplicateEntryException {
		try {
			ElectionInformationContent informationContent = electionInformationContentRepository.save(entity);
			secureLoggerWriter.log(Level.INFO,
				new LogContent.LogContentBuilder().logEvent(ElectionInformationLogEvents.BALLOT_TEXT_SAVED)
					.objectId("electionInfo").user("admin").electionEvent(entity.getElectionEventId())
					.additionalInfo(ElectionInformationLogConstants.INFO_TRACK_ID, trackId.getTrackId())
					.createLogInfo());
			return informationContent;
		} catch (DuplicateEntryException ex) {
			secureLoggerWriter.log(Level.INFO,
				new LogContent.LogContentBuilder().logEvent(ElectionInformationLogEvents.ERROR_SAVING_BALLOT_TEXT)
					.objectId("electionInfo").user("admin").electionEvent(entity.getElectionEventId())
					.additionalInfo(ElectionInformationLogConstants.INFO_TRACK_ID, trackId.getTrackId())
					.additionalInfo(ElectionInformationLogConstants.INFO_ERR_DESC, ex.getMessage())
					.createLogInfo());
			throw ex;
		}
	}
}
