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

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

import com.patrikdufresne.ilp.Linear;
import com.patrikdufresne.ilp.LinearProblem;
import com.patrikdufresne.ilp.util.Linears;

/**
 * Minimize the number of employee assigned.
 * 
 * @author Patrik Dufresne
 */
@SuppressWarnings("unqualified-field-access")
public class MinEmployeeAssigned extends AbstractConstraintRunnable {

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

    /**
     * The constraint's name.
     */
    private static final String CONSTRAINT_NAME = "SUM from{i} to{n} xi <= %d";

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

    /**
     * If sets, define the best known solution according to the snapshot.
     */
    private Integer snapshotUpperBound;

    /**
     * Public constructor.
     * 
     * @param problem
     *            reference to ProblemBuilder
     */
    public MinEmployeeAssigned(ProblemBuilder problem) {
        super(problem);
        setFeasibilityPumpHeuristic(true);
    }

    @Override
    protected void feasible() {
        // Get the objective value
        Integer value = Integer.valueOf(pb.lp.getObjectiveValue().intValue());
        fixMaximumNumberOfEmployee(value);
    }

    /**
     * Create a redefine the constraint to sets the maximum number of employees.
     * 
     * @param value
     *            the maximum number of employee.
     */
    private void fixMaximumNumberOfEmployee(Integer value) {
        // Create or redefine the constraint upper bound.
        String name = String.format(CONSTRAINT_NAME, value);
        if (this.constraint != null) {
            this.constraint.dispose();
        }
        this.constraint = pb.lp.addConstraint(name, linear, null, value);
        LOGGER.info("Minimum number of employees: {}", value);
        this.feasible = true;
    }

    @Override
    protected boolean setUp() {
        LOGGER.debug("Minimize number of employee.");
        // Create the following linear function : SUM xi
        Double[] coefs = new Double[pb.xi.length];
        Arrays.fill(coefs, ONE);
        this.linear = pb.lp.createLinear(coefs, pb.xi);
        // TODO Use the snapshot value to restrict the feasibility and force
        // the solver to improve the solution.
        // To reduce the computing time, sets a maximum using a constraint.
        if (pb.snapshot != null) {
            this.snapshotUpperBound = Integer.valueOf(Linears.compute(linear, pb.snapshot).intValue());
            if (ZERO.equals(this.snapshotUpperBound)) {
                this.snapshotUpperBound = null;
                this.feasible = false;
                return false;
            }
            // Create a constraint to force the solver to improve the
            // current solution.
            Integer upperBound = Integer.valueOf(this.snapshotUpperBound.intValue() - 1);
            String name = String.format(CONSTRAINT_NAME, upperBound);
            this.constraint = pb.lp.addConstraint(name, linear, null, upperBound);
        }
        // Set the linear as an objective.
        pb.lp.setObjectiveLinear(this.linear);
        pb.lp.setObjectiveDirection(LinearProblem.MINIMIZE);
        return true;
    }

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

    @Override
    protected void unfeasible() throws GeneratePlanifException {
        if (this.snapshotUpperBound != null) {
            fixMaximumNumberOfEmployee(this.snapshotUpperBound);
        } else {
            // It's a maximization problem, it' must be feasible.
            throwProblemUnFeasible();
        }
    }
}