/*
 * 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.sdm.infrastructure.ballottext;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.annotation.PostConstruct;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import com.orientechnologies.common.exception.OException;
import com.orientechnologies.orient.core.record.impl.ODocument;
import com.scytl.products.ov.sdm.application.exception.DatabaseException;
import com.scytl.products.ov.sdm.domain.model.ballottext.BallotText;
import com.scytl.products.ov.sdm.domain.model.ballottext.BallotTextRepository;
import com.scytl.products.ov.sdm.infrastructure.AbstractEntityRepository;
import com.scytl.products.ov.sdm.infrastructure.DatabaseManager;
import com.scytl.products.ov.sdm.infrastructure.JsonConstants;
import com.scytl.products.ov.sdm.domain.model.status.Status;

/**
 * Implementation of the Ballot Repository
 */
@Repository
public class BallotTextRepositoryImpl extends AbstractEntityRepository
        implements BallotTextRepository {

    /**
     * Constructor
     *
     * @param databaseManager
     *            the injected database manager
     */
    @Autowired
    public BallotTextRepositoryImpl(
            final DatabaseManager databaseManager) {
        super(databaseManager);
    }

    @PostConstruct
    @Override
    public void initialize() throws DatabaseException {
        super.initialize();
    }

    @Override
    public void updateSignedBallotText(final String ballotTextId,
            final String signedBallotText) {
        try {
            ODocument text = getDocument(ballotTextId);
            text.field(JsonConstants.JSON_ATTRIBUTE_NAME_SIGNED_OBJECT,
                signedBallotText);
            text.field(JsonConstants.JSON_ATTRIBUTE_NAME_STATUS, Status.SIGNED.name());
            saveDocument(text);
        } catch (OException e) {
            throw new DatabaseException(
                "Failed to update signed ballot text.", e);
        }
    }

    @Override
    public List<String> listSignatures(final Map<String, Object> criteria)
            throws DatabaseException {
        List<ODocument> documents;
        try {
            documents = listDocuments(criteria);
        } catch (OException e) {
            throw new DatabaseException("Failed to list signatures.", e);
        }
        List<String> signatures = new ArrayList<>(documents.size());
        for (ODocument document : documents) {
            signatures.add(document.field(
                JsonConstants.JSON_ATTRIBUTE_NAME_SIGNED_OBJECT,
                String.class));
        }
        return signatures;
    }

    @Override
    protected String entityName() {
        return BallotText.class.getSimpleName();
    }
}
