/**
 * 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;

import com.patrikdufresne.ilp.util.BoundSnapshot;
import com.patrikdufresne.ilp.util.Variables;

/**
 * This runnable is used to check feasibility of assigning employee to preferred team.
 * 
 * @author Patrik Dufresne
 */
public class CheckPreferredTeam extends SolveRunnable {

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

    /**
     * Bound snapshot used to restore the bound is the problem is unfeasible.
     */
    private BoundSnapshot boundSnapshot;

    /**
     * The employee.
     */
    private int i;

    /**
     * The team.
     */
    private int j;

    /**
     * Create a new runnable to assign employee <code>i</code> to preferred team <code>j</code>
     * 
     * @param problem
     *            reference to ProblemBuilder
     * @param i
     *            the employee
     * @param j
     *            the team
     * @param rtj
     *            True to assign the employee to tasks really in team.
     */
    public CheckPreferredTeam(ProblemBuilder problem, int i, int j) {
        super(problem);
        this.i = i;
        this.j = j;
        setFeasibilityPumpHeuristic(true);
    }

    @Override
    protected void feasible() {
        LOGGER.info("Employee {} assign to team {}.", pb.employeeToString(i), pb.teamToString(j));
    }

    /**
     * This implementation is using the snapshot to determine if the employee is laready assigned to the team. If so, it
     * also check if the employee if assign only to unswappable task.
     * <p>
     * If the employee is assign to swappable task, this runnable will try to improve the current solution.
     */
    @Override
    protected boolean setUp() {
        // Check if employee can be assigned to team j
        if (pb.xij[i] == null || pb.xij[i][j] == null) {
            this.feasible = false;
            return false;
        }
        // Take bounds snapshot before changing them
        this.boundSnapshot = BoundSnapshot.create(pb.variablesForEmployee(i));
        // Fix to zero (0) xik, xij and xi variables not corresponding to
        // the team for employee i. Be careful not to change fixed
        // variables.
        for (int j2 = 0; j2 < pb.xij[this.i].length; j2++) {
            if (j2 != this.j) {
                for (int k = 0; k < pb.xijk[this.i][j2].length; k++) {
                    if (pb.xijk[this.i][j2][k] != null && !Variables.isFixed(pb.xijk[this.i][j2][k])) {
                        pb.xijk[this.i][j2][k].setLowerBound(ZERO);
                        pb.xijk[this.i][j2][k].setUpperBound(ZERO);
                    }
                }
            }
            if (pb.xij[this.i][j2] != null && !Variables.isFixed(pb.xij[i][j2])) {
                pb.xij[this.i][j2].setLowerBound(this.j == j2 ? ONE : ZERO);
                pb.xij[this.i][j2].setUpperBound(this.j == j2 ? ONE : ZERO);
            }
        }
        // Don't create any constraint to force the employee to work a
        // minimum number of time on the team. OItherwise it will break the
        // non-availability handler. See ticket #191.
        // Sets the objective
        pb.lp.setObjectiveLinear(null);
        LOGGER.debug("Check feasiblility with employee {} " + "working on team {}.", pb.employeeToString(i), pb.teamToString(j));
        return true;
    }

    @Override
    protected void tearDown() throws GeneratePlanifException {
        // Nothing to do.
    }

    @Override
    protected void unfeasible() {
        if (this.boundSnapshot != null) {
            // Restore the bound snapshot.
            this.boundSnapshot.restore();
            this.boundSnapshot = null;
            LOGGER.info("Can't assign " + "employee {} to team {}", pb.employeeToString(i), pb.teamToString(j));
        }
    }
}