/*
 * 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.mixnet.webapp.mvc;

import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import java.net.URI;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

/**
 * The results of calling /execute on the mix-dec-val controller of the cryptoservices.
 */
public class MixDecValResult {

    private final List<Path> mixingDirectories;

    private final Throwable error;

    /**
     * Constructor to be used by the JSON deserialiser.
     * Please note that, since the current implementation does not support deserialising from Path objects, the mixing
     * directories must be passed in as strings, and converted internally. Also, the serialiser converts Path objects to
     * their URI representation, so that must be taken into account when converting back.
     *
     * @param mixingDirectories the mixing directories as URIs.
     * @param error an error
     */
    @JsonCreator
    private MixDecValResult(@JsonProperty("mixingDirectories") List<String> mixingDirectories,
            @JsonProperty("error") Throwable error) {
        // Populate the mixing directories if there is a list thereof.
        this.mixingDirectories = mixingDirectories == null
                ? Collections.emptyList()
                : mixingDirectories.stream().map(mixingDirectory -> {
                    // Assume the mixing directory is a URI, as this is what the
                    // object mapper produces on serialisation. If it fails, try
                    // creating the path from the string.
                    try {
                        return Paths.get(URI.create(mixingDirectory));
                    } catch (IllegalArgumentException e) {
                        return Paths.get(mixingDirectory);
                    }
                }).collect(Collectors.toList());

        this.error = error;
    }

    public MixDecValResult(List<Path> mixingDirectories) {
        this.mixingDirectories = mixingDirectories;
        this.error = null;
    }

    public MixDecValResult(Throwable error) {
        this.mixingDirectories = Collections.emptyList();
        this.error = error;
    }

    public List<Path> getMixingDirectories() {
        return mixingDirectories;
    }

    public Throwable getError() {
        return error;
    }
}
