/**
 * Copyright (C) 2019 Patrik Dufresne Service Logiciel <info@patrikdufresne.com>
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 3 of the License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with this program; if not, write to the Free Software Foundation,
 * Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
 */
package com.planimod.core.planif;

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

/**
 * Used to maximize the use of senior employee by checking if their is solutions without least senior employee.
 * <p>
 * This implementation is using the {@link CheckEmployeeNotWorking} runnables to avoid assignment of less senior
 * employees.
 * 
 * @author Patrik Dufresne
 */
@SuppressWarnings("unqualified-field-access")
public class MaxSeniorEmployee extends SolveRunnable {

    private static final transient Logger LOGGER = LoggerFactory.getLogger(MaxSeniorEmployee.class);

    /**
     * The upper employee index to maximize.
     */
    private int from;

    /**
     * Array of runnable used internally.
     */
    private CheckEmployeeNotWorking[] runnables;

    /**
     * Public constructor.
     * 
     * @param problem
     *            reference to ProblemBuilder
     */
    public MaxSeniorEmployee(ProblemBuilder problem) {
        super(problem);
        setFeasibilityPumpHeuristic(true);
        this.runnables = new CheckEmployeeNotWorking[problem.xi.length];
    }

    /**
     * Check if every higher employee then <code>i</code> and <code>i</code> it self is part of the solution.
     * 
     * @param i
     *            the employee index
     * @return True if every higher employees are part of the solution.
     */
    private boolean checkHigherEmployeesAssigned(int from, int to) {
        if (pb.snapshot == null) {
            return false;
        }
        // Check if every other employee are schedule to work.
        int i2 = to;
        while (i2 >= from && ONE.equals(pb.snapshot.get(pb.xi[i2]))) {
            i2--;
        }
        return i2 < from;
    }

    /**
     * Restore the previous snapshot.
     */
    public void engage(int from) {
        // Release all the constraints.
        for (int i = from; i < pb.xi.length; i++) {
            if (this.runnables[i] != null) {
                this.runnables[i].engage();
            }
        }
    }

    /**
     * This implementation will call run. TODO improve performance by checking satisfiability using previous snapshot.
     * 
     * @param from
     * @throws GeneratePlanifException
     */
    public void engageOrRun(int from) throws GeneratePlanifException {
        run(from);
    }

    /**
     * 
     */
    public void release(int from) {
        // Release all the constraints.
        for (int i = from; i < pb.xi.length; i++) {
            if (this.runnables[i] != null) {
                this.runnables[i].release();
            }
        }
    }

    @Override
    public boolean run() throws GeneratePlanifException {
        this.from = 0;
        return super.run();
    }

    /**
     * Recompute this objective from employee define by <code>from</code>. The employee index is inclusive.
     * 
     * @param from
     *            the employee index to recompute from (inclusive).
     * @throws GeneratePlanifException
     */
    public boolean run(int from) throws GeneratePlanifException {
        this.from = from;
        return super.run();
    }

    @Override
    protected boolean runSolver() throws GeneratePlanifException {
        for (int i = pb.xi.length - 1; i >= this.from; i--) {
            // Check if every higher employee are working, is so there
            // is no
            // need to compute any more
            if (checkHigherEmployeesAssigned(this.from, i)) {
                // All higher employee are working, leave the function
                LOGGER.info("All higher employees are part " + "of the solution.");
                return true;
            }
            if (this.runnables[i] == null) {
                this.runnables[i] = new CheckEmployeeNotWorking(pb, i);
            }
            this.runnables[i].run();
            // Update the progress or leave
            pb.worked(0);
        }
        return true;
    }

    @Override
    protected boolean setUp() throws GeneratePlanifException {
        LOGGER.debug("Maximize use of senior employees.");
        return true;
    }

    @Override
    protected void tearDown() throws GeneratePlanifException {
        // Remove the objective function
        pb.lp.setObjectiveLinear(null);
    }
}