/*
 * 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.commons.beans;

import org.apache.commons.lang3.ArrayUtils;

import java.util.Arrays;
import java.util.List;
import java.util.TreeSet;

/**
 * Encapsulates a permutation.
 */
public class Permutation {

    private final int[] permutation;

    /**
     * Create a Permutation setting the received permutation.
     * 
     * @param permutation
     *            the permutation to set in this Permutation.
     */
    public Permutation(final int[] permutation) {

        validateInput(permutation);

        this.permutation = Arrays.copyOf(permutation, permutation.length);

    }

    public int getLength() {
        return permutation.length;
    }

    public int destinationOf(final int i) {
        return permutation[i];
    }

	private static void validateInput(final int[] permutation) {

		if ((permutation == null) || (permutation.length == 0)) {
			throw new IllegalArgumentException("The permutation must be initialized and contain at least 1 element.");
		}

		final List<Integer> permutationAsList = Arrays.asList(ArrayUtils.toObject(permutation));

		final TreeSet<Integer> uniqueIndexes = new TreeSet<>(permutationAsList);

		if (permutation.length != uniqueIndexes.size()) {
			throw new IllegalArgumentException("The given permutation contains repeated elements.");
		}

		if ((uniqueIndexes.first() != 0) || (uniqueIndexes.last() != (permutation.length - 1))) {
			throw new IllegalArgumentException("The given permutation contains invalid indexes.");
		}
	}

}
