/*
 * 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.adminboard.AdminBoard;
import com.scytl.products.ov.au.services.domain.model.adminboard.AdminBoardRepository;
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 AdminBoardRepositoryDecorator implements AdminBoardRepository {

	@Inject
	@Delegate
	private AdminBoardRepository adminBoardRepository;

	@Inject
	private TrackIdInstance trackId;

	@Inject
	private SecureLoggingWriter secureLoggingWriter;

	@Override
	public AdminBoard save(final AdminBoard entity) throws DuplicateEntryException {
		try {
            final AdminBoard adminBoard = adminBoardRepository.save(entity);
            secureLoggingWriter.log(Level.INFO,
                new LogContent.LogContentBuilder().logEvent(AuthenticationLogEvents.ADMIN_BOARD_SAVED)
                    .objectId(entity.getAdminBoardId()).user("admin")
                    .electionEvent(entity.getElectionEventId())
                    .additionalInfo(AuthenticationLogConstants.INFO_TRACK_ID, trackId.getTrackId())
					.createLogInfo());
            return adminBoard;
        } catch (DuplicateEntryException ex) {
            secureLoggingWriter.log(Level.ERROR,
                new LogContent.LogContentBuilder().logEvent(AuthenticationLogEvents.ERROR_SAVING_ADMIN_BOARD)
                    .objectId(entity.getAdminBoardId()).user("admin")
                    .electionEvent(entity.getElectionEventId())
                    .additionalInfo(AuthenticationLogConstants.INFO_TRACK_ID, trackId.getTrackId())
                    .additionalInfo(AuthenticationLogConstants.INFO_ERR_DESC, ex.getMessage())
                    .createLogInfo());
            throw ex;
		}
	}
}
