/**
 * 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 java.util.List;

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.planimod.core.EmployeePreference;
import com.planimod.core.Section;

/**
 * Used to maximize the number of assigned to preferred section.
 * <p>
 * This objective doesn't maximize the preferred section of swappable task. See bug #68.
 * 
 * @author Patrik Dufresne
 */
@SuppressWarnings("unqualified-field-access")
public class MaxPreferredSection extends SolveRunnable {

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

    /**
     * The employee's preferred section or null.
     */
    private int a;

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

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

    /**
     * The linear being maximized.
     */
    private Linear linear;

    /**
     * When this value is set, we have determine a lower bound using the snapshot value. In case we can't improve this
     * value, the problem will be unfeasible and as such, we must sets this value to the constraint.
     */
    private Number snapshotLowerBound;

    /**
     * Default constructor to maximize the preferred section of the employee <code>i</code>.
     * 
     * @param problem
     *            reference to ProblemBuilder
     * 
     * @param i
     *            the employee
     */
    public MaxPreferredSection(ProblemBuilder problem, int i) {
        super(problem);
        this.i = i;
        this.a = -1;
        setFeasibilityPumpHeuristic(true);
    }

    private void assignEmployeeToSection(Integer lowerBound) {
        // Fix all the xik variables where the employee is working on the
        // section.
        for (int j2 = 0; j2 < pb.xijk[i].length; j2++) {
            for (int k = 0; k < pb.xijk[i][j2].length; k++) {
                // Check if the xijk is assigned to the employee and is
                // matching the preferred section.
                if (pb.xijk[i][j2][k] != null && pb.siTable.kInSa(k, this.a) && ONE.equals(pb.snapshot.get(pb.xijk[i][j2][k]))) {
                    // Find the matching Gl
                    for (List<Integer> coefs : pb.table.glIntersectTask(k)) {
                        // For this Gl, remove any tasks not matching the
                        // section.
                        for (int k2 = 0; k2 < coefs.size(); k2++) {
                            if (pb.xijk[i][j2][k2] != null && !pb.siTable.kInSa(k2, a) && ONE.equals(coefs.get(k2))) {
                                pb.xijk[i][j2][k2].setLowerBound(ZERO);
                                pb.xijk[i][j2][k2].setLowerBound(ZERO);
                            }
                        }
                    }
                }
            }
        }
        // Add a constraint to make sure the employee is assigned to the
        // preferred section.
        String name = String.format("SUM from{k in Si} xijk >=%d, for i=%d", lowerBound, i);
        if (this.constraint != null) {
            this.constraint.dispose();
        }
        this.constraint = pb.lp.addConstraint(name, this.linear, lowerBound, null);
    }

    @Override
    protected void feasible() {
        // Assign employee to preferred section.
        Integer value = Integer.valueOf(pb.lp.getObjectiveValue().intValue());
        assignEmployeeToSection(value);
    }

    @Override
    protected boolean setUp() {
        // Check if the employee is schedule to work according to snapshot
        if (pb.snapshot != null && ZERO.equals(pb.snapshot.get(pb.xi[i]))) {
            this.feasible = false;
            return false;
        }
        // Check if the employee as preferences
        EmployeePreference pref = pb.preferences.get(i);
        Section section;
        if (pref == null || (section = pref.getPreferredSection()) == null) {
            this.feasible = false;
            return false;
        }
        // Check if preferred section is part of the planif.
        this.a = pb.siTable.indexOf(section);
        if (this.a < 0) {
            this.feasible = false;
            return false;
        }
        // Build the linear expression to be maximize
        this.linear = pb.lp.createLinear();
        for (int j = 0; j < pb.xijk[i].length; j++) {
            for (int k = 0; k < pb.xijk[i][j].length; k++) {
                // Add the variable to the linear only if it's part of the
                // Team as real (see bug #68) and part of the preferred
                // section.
                if (pb.xijk[i][j][k] != null && pb.table.kInRTj(k, j) && pb.siTable.kInSa(k, a)) {
                    this.linear.add(pb.lp.createTerm(ONE, pb.xijk[i][j][k]));
                }
            }
        }
        if (this.linear.size() == 0) {
            this.feasible = false;
            return false;
        }
        // Also sets the linear with a minimum value using a constraints. To
        // improve performance, compute the minimum value using the
        // snapshot.
        int lowerBound = Math.max(ZERO.intValue(), (pb.snapshot != null ? (snapshotLowerBound = Linears.compute(this.linear, pb.snapshot)) : ZERO).intValue());
        String name = String.format("SUM from{k in Si} xik >=%d, for i=%d", Integer.valueOf(lowerBound + 1), Integer.valueOf(i));
        this.constraint = pb.lp.addConstraint(name, this.linear, Integer.valueOf(lowerBound + 1), null);
        // Set the linear as an objective
        pb.lp.setObjectiveLinear(this.linear);
        pb.lp.setObjectiveDirection(LinearProblem.MAXIMIZE);
        LOGGER.info("Maximize employee {} preferred section.", pb.employeeToString(i));
        return true;
    }

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

    @Override
    protected void unfeasible() {
        if (this.snapshotLowerBound != null) {
            assignEmployeeToSection(Integer.valueOf(snapshotLowerBound.intValue()));
        } else if (a >= 0) {
            LOGGER.warn("Employee {} can't be assigned to " + "preferred section.", pb.employeeToString(i));
        }
    }
}