/**
 * Copyright (c) 2017 Siemens AG
 * All rights reserved.
 * 
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 * 
 * 1) Redistributions of source code must retain the above copyright notice, this
 *    list of conditions and the following disclaimer.
 * 
 * 2) Redistributions in binary form must reproduce the above copyright notice,
 *    this list of conditions and the following disclaimer in the documentation
 *    and/or other materials provided with the distribution.
 * 
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
 * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
 * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */
package at.ac.tuwien.kr.alpha.core.solver;

import static at.ac.tuwien.kr.alpha.core.test.util.TestUtils.buildSolverForRegressionTest;
import static at.ac.tuwien.kr.alpha.core.test.util.TestUtils.runWithTimeout;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.Random;

import org.junit.jupiter.api.Disabled;

import at.ac.tuwien.kr.alpha.api.AnswerSet;
import at.ac.tuwien.kr.alpha.api.programs.ASPCore2Program;
import at.ac.tuwien.kr.alpha.api.programs.atoms.Atom;
import at.ac.tuwien.kr.alpha.api.programs.terms.Term;
import at.ac.tuwien.kr.alpha.commons.Predicates;
import at.ac.tuwien.kr.alpha.commons.programs.Programs;
import at.ac.tuwien.kr.alpha.commons.programs.Programs.ASPCore2ProgramBuilder;
import at.ac.tuwien.kr.alpha.commons.programs.atoms.Atoms;
import at.ac.tuwien.kr.alpha.commons.programs.terms.Terms;
import at.ac.tuwien.kr.alpha.core.parser.ProgramParserImpl;

public class ThreeColouringRandomGraphTest {
	
	private static final long DEBUG_TIMEOUT_FACTOR = 5;
	
	@RegressionTest
	public void testV3E3(RegressionTestConfig cfg) {
		long timeout = 1000L;
		runWithTimeout(cfg, timeout, DEBUG_TIMEOUT_FACTOR, () -> testThreeColouring(3, 3, cfg));
	}

	@RegressionTest
	@Disabled("disabled to save resources during CI")
	public void testV10E18(RegressionTestConfig cfg) {
		long timeout = 10000L;
		runWithTimeout(cfg, timeout, DEBUG_TIMEOUT_FACTOR, () -> testThreeColouring(10, 18, cfg));
	}

	@RegressionTest
	@Disabled("disabled to save resources during CI")
	public void testV20E38(RegressionTestConfig cfg) {
		long timeout = 10000L;
		runWithTimeout(cfg, timeout, DEBUG_TIMEOUT_FACTOR, () -> testThreeColouring(20, 38, cfg));
	}

	@RegressionTest
	@Disabled("disabled to save resources during CI")
	public void testV30E48(RegressionTestConfig cfg) {
		long timeout = 10000L;
		runWithTimeout(cfg, timeout, DEBUG_TIMEOUT_FACTOR, () -> testThreeColouring(30, 48, cfg));
	}

	@RegressionTest
	@Disabled("disabled to save resources during CI")
	public void testV200E300(RegressionTestConfig cfg) {
		long timeout = 60000L;
		runWithTimeout(cfg, timeout, DEBUG_TIMEOUT_FACTOR, () -> testThreeColouring(200, 300, cfg));
	}

	@RegressionTest
	@Disabled("disabled to save resources during CI")
	public void testV300E200(RegressionTestConfig cfg) {
		long timeout = 60000L;
		runWithTimeout(cfg, timeout, DEBUG_TIMEOUT_FACTOR, () -> testThreeColouring(300, 200, cfg));
	}

	@RegressionTest
	@Disabled("disabled to save resources during CI")
	public void testV300E300(RegressionTestConfig cfg) {
		long timeout = 60000L;
		runWithTimeout(cfg, timeout, DEBUG_TIMEOUT_FACTOR, () -> testThreeColouring(300, 300, cfg));
	}

	private void testThreeColouring(int nVertices, int nEdges, RegressionTestConfig cfg) {
		ASPCore2Program tmpPrg = new ProgramParserImpl().parse(
				"blue(N) :- v(N), not red(N), not green(N)." +
				"red(N) :- v(N), not blue(N), not green(N)." +
				"green(N) :- v(N), not red(N), not blue(N)." +
				":- e(N1,N2), blue(N1), blue(N2)." +
				":- e(N1,N2), red(N1), red(N2)." +
				":- e(N1,N2), green(N1), green(N2).");
		ASPCore2ProgramBuilder prgBuilder = Programs.builder(tmpPrg);
		prgBuilder.addFacts(createVertices(nVertices));
		prgBuilder.addFacts(createEdges(nVertices, nEdges));
		ASPCore2Program program = prgBuilder.build();
		maybeShuffle(program);

		@SuppressWarnings("unused")
		Optional<AnswerSet> answerSet = buildSolverForRegressionTest(program, cfg).stream().findAny();
		//System.out.println(answerSet);

		// TODO: check correctness of answer set
	}

	@SuppressWarnings("unused")
	private void maybeShuffle(ASPCore2Program program) {

		// TODO: switch on if different rule orderings in the encoding are desired (e.g. for benchmarking purposes)
		// FIXME since InputProgram is immutable this needs to be reworked a bit if used
		// Collections.reverse(program.getRules());
		// Collections.shuffle(program.getRules());
		// Collections.reverse(program.getFacts());
		// Collections.shuffle(program.getFacts());
	}

	private List<Atom> createVertices(int n) {
		List<Atom> facts = new ArrayList<>(n);
		for (int i = 0; i < n; i++) {
			facts.add(fact("v", i));
		}
		return facts;
	}

	private List<Atom> createEdges(int vertices, int edges) {
		Random rand = new Random(0);
		List<Atom> facts = new ArrayList<>(edges);
		for (int i = 0; i < edges; i++) {
			int v1 = 0;
			int v2 = 0;
			while (v1 == v2) {
				v1 = rand.nextInt(vertices);
				v2 = rand.nextInt(vertices);
			}
			facts.add(fact("e", v1, v2));
			facts.add(fact("e", v2, v1));
		}
		return facts;
	}

	private Atom fact(String predicateName, int... iTerms) {
		List<Term> terms = new ArrayList<>(1);
		for (int i : iTerms) {
			terms.add(Terms.newConstant(i));
		}
		return Atoms.newBasicAtom(Predicates.getPredicate(predicateName, iTerms.length), terms);
	}
}
