/**
 * 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.Constraint;
import com.patrikdufresne.ilp.Linear;
import com.patrikdufresne.ilp.LinearProblem;
import com.patrikdufresne.ilp.util.Linears;
import com.patrikdufresne.ilp.util.Variables;
import com.planimod.core.EmployeePreference;
import com.planimod.core.Position;
import com.planimod.core.Task;
import com.planimod.core.Team;

/**
 * This runnable is used to assigned employee to it's preferred position.
 * 
 * @author Patrik Dufresne
 */
@SuppressWarnings("unqualified-field-access")
public class MaxPreferredPosition extends SolveRunnable {

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

    /** The constraints name. */
    private static final String CONSTRAINT_NAME = "MaxPreferredPosition: SUM from{k in PPi} xik] >= %d, for i=%d";

    /** Constraint to check feasibility */
    private Constraint constraint;

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

    /** Employee preferred position team */
    private int j;

    /** Employee preferred position */
    private Position pos;

    private boolean released;

    private Linear linear;

    /**
     * Create a new runnable to maximize employee <code>i</code> preferred position.
     * 
     * @param problem
     *            reference to ProblemBuilder
     * 
     * @param i
     *            the employee
     * @param loosly
     *            True to assign the employee to the preferred position event if it's brake the max-senior-employee rule.
     */
    public MaxPreferredPosition(ProblemBuilder problem, int i) {
        super(problem);
        this.i = i;
        setFeasibilityPumpHeuristic(true);
    }

    private void assignEmployeeToPreferredPosition() throws GeneratePlanifException {
        // For each k, fix the xijk variables to ZERO or ONE if the employee
        // i is assigned to his preferred position.
        for (int k = 0; k < pb.xijk[i][j].length; k++) {
            if (pb.xijk[i][j][k] != null
                    && pb.table.kInRTj(k, j)
                    && ONE.equals(pb.snapshot.get(pb.xijk[i][j][k]))
                    && pos.equals(pb.tasks.get(k).getPosition())) {
                // The employee i is assigned to preferred position k, fix
                // the variables xijk, for each i, and each j.
                for (int j2 = 0; j2 < pb.xijk[i].length; j2++) {
                    if (pb.xijk[i][j2][k] != null) {
                        pb.xijk[i][j2][k].setLowerBound(ONE);
                        pb.xijk[i][j2][k].setUpperBound(ONE);
                    }
                }
            }
        }
        // Fix to zero (0) xijk and xij variables not corresponding to
        // the team j 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);
            }
        }
        LOGGER.info("Employee {} assigned to preferred position.", pb.employeeToString(i));
        // Override the feasible variable.
        this.feasible = true;
    }

    @Override
    protected void feasible() throws GeneratePlanifException {
        assignEmployeeToPreferredPosition();
    }

    @Override
    protected boolean runSolver() throws GeneratePlanifException {
        // The first time, we run the solver without releasing the
        // max-senior-employee rule to check if the employee can work
        // on every preferred position.
        if (super.runSolver()) {
            return true;
        }
        // If it didn't work, be more permissive. Allow to broke
        // max-senior-employee rule and to be partially assign.
        this.constraint.setLowerBound(ONE);
        pb.lp.setObjectiveLinear(this.linear);
        pb.lp.setObjectiveDirection(LinearProblem.MAXIMIZE);
        this.released = true;
        pb.maxSeniorEmployee.release(i + 1);
        // Try to assign the employee to his preferred position again.
        return super.runSolver();
    }

    @Override
    protected boolean setUp() {
        // Check if the employee has a preferred position
        EmployeePreference pref = pb.preferences.get(i);
        Team team;
        if (pref == null || (this.pos = pref.getPreferredPosition()) == null || (team = pref.getPreferredPositionTeam()) == null) {
            this.feasible = false;
            return false;
        }
        this.j = pb.table.indexOf(team);
        if (j < 0) {
            this.feasible = false;
            return false;
        }
        // Build the a linear with the preferred position tasks.
        this.linear = pb.lp.createLinear();
        for (int k = 0; k < pb.tasks.size(); k++) {
            Task task = pb.tasks.get(k);
            if (pb.xijk[i][j][k] != null && this.pos.equals(task.getPosition()) && pb.table.kInRTj(k, j) && !ProblemBuilder.isFixedToZero(pb.xijk[i][j][k])) {
                linear.add(pb.lp.createTerm(1, pb.xijk[i][j][k]));
            }
        }
        if (linear.size() == 0) {
            // Can't assign employee if no task are available.
            this.feasible = false;
            return false;
        }
        // Simple solution to fix ticket #263. Create a constraint to force the employee to work on every task matching
        // the preferred position without consideration of the Gl.
        String name = String.format(CONSTRAINT_NAME, linear.size(), Integer.valueOf(i));
        this.constraint = pb.lp.addConstraint(name, linear, linear.size(), null);
        LOGGER.debug("Assign employee {} to preferred position.", pb.employeeToString(i));
        return true;
    }

    @Override
    protected void tearDown() throws GeneratePlanifException {
        // In all cases, the constraint is unless because the variables got fixed.
        if (this.constraint != null) {
            this.constraint.dispose();
            this.constraint = null;
        }
        // Remove objective
        pb.lp.setObjectiveLinear(null);
        if (this.released) {
            if (feasible) {
                pb.maxSeniorEmployee.run(i + 1);
            } else {
                pb.maxSeniorEmployee.engage(i + 1);
            }
        }
    }

    @Override
    protected void unfeasible() throws GeneratePlanifException {
        if (pos != null && j >= 0) {
            LOGGER.info("Employee {} not assigned to preferred position.", pb.employeeToString(i));
        }
    }
}