/*
 * 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.channel.cc.orchestrator.mixdec.domain.services;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.UUID;

import javax.inject.Inject;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.scytl.products.ov.channel.cc.orchestrator.commons.config.QueuesConfig;
import com.scytl.products.ov.channel.cc.orchestrator.commons.config.TopicsConfig;
import com.scytl.products.ov.channel.cc.orchestrator.commons.infrastructure.persistence.Jdbc;
import com.scytl.products.ov.channel.cc.orchestrator.commons.infrastructure.persistence.PartialResultsRepository;
import com.scytl.products.ov.commons.dto.KeyCreationDTO;
import com.scytl.products.ov.commons.messaging.MessageListener;
import com.scytl.products.ov.commons.messaging.MessagingException;
import com.scytl.products.ov.commons.messaging.MessagingService;
import com.scytl.products.ov.commons.safestream.StreamSerializableObjectWriterImpl;

/**
 * Consumer of the generation of MixDec keys.
 */
@MixDecKeyGeneration
@Contributions
public class MixDecKeyGenerationConsumer implements MessageListener {
    private static final Logger LOG = LoggerFactory.getLogger("std");

    @Inject
    private MessagingService messagingService;

    @Inject
    @Jdbc
    private PartialResultsRepository<byte[]> repository;

    @Override
    public void onMessage(Object message) {
        KeyCreationDTO result = (KeyCreationDTO) message;
        LOG.info(
            "OR - Message accepted in " + this.getClass().getSimpleName());

        persistPartialResult(result);
        sendPartialResultsReadyIfNecessary(result);
    }

    private void sendPartialResultsReadyIfNecessary(
            KeyCreationDTO result) {
        UUID correlationId = result.getCorrelationId();
        if (repository.hasAll(correlationId,
            QueuesConfig.MIX_DEC_KEY_GENERATION_RES_QUEUES.length)) {
            LOG.info("OR - All partial results are ready in "
                + getClass().getSimpleName());
            byte[] message = encodeCorrelationId(correlationId);
            try {
                messagingService.send(TopicsConfig.HA_TOPIC, message);
            } catch (MessagingException e) {
                throw new IllegalStateException(
                    "Failed to send notification.", e);
            }
            LOG.info("OR - Correlation identifier {} is sent to {}.",
                correlationId, TopicsConfig.HA_TOPIC);
        }
    }

    private byte[] encodeCorrelationId(UUID correlationId) {
        return ByteBuffer.allocate(Long.BYTES * 2)
            .putLong(correlationId.getMostSignificantBits())
            .putLong(correlationId.getLeastSignificantBits()).array();
    }

    private void persistPartialResult(KeyCreationDTO result) {
        LOG.info("OR - Persisting partial result in "
            + getClass().getSimpleName());

        UUID key = result.getCorrelationId();

        byte[] bytes = serializeKeyCreationDTO(result);

        repository.save(key, bytes);
    }

    private byte[] serializeKeyCreationDTO(KeyCreationDTO message) {
        try {
            return new StreamSerializableObjectWriterImpl().write(message);
        } catch (IOException e) {
            throw new IllegalStateException(
                "Failed to serialize key creation DTO.", e);
        }
    }
}
