/**
 * 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.Linear;
import com.patrikdufresne.ilp.util.BoundSnapshot;
import com.planimod.core.Employee;
import com.planimod.core.EmployeePreference;
import com.planimod.core.Team;

/**
 * Maximize the preferred seniority used in the planif. In case not all the employees with preferred seniority can be
 * used, a callbackContinue will be used to ask the user if the generation should continue or not.
 * 
 * @author Patrik Dufresne
 * 
 */
public class MaxPreferredSeniority extends SolveRunnable {

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

    /**
     * The employee.
     */
    private final Employee employee;

    /**
     * The employee index.
     */
    final int i;

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

    /**
     * The bounds before applying the unavailability
     */
    private BoundSnapshot originalBound;

    /**
     * Default constructor to maximize the preferred team of the employee <code>i</code>.
     * 
     * @param problem
     *            reference to ProblemBuilder
     * 
     * @param i
     *            the employee
     */
    public MaxPreferredSeniority(ProblemBuilder problem, int i) {
        super(problem);
        this.i = i;
        this.employee = pb.employees.get(i);
    }

    /**
     * Return the preferred team of the employee i. If the employee i has no preference, returns null.
     * 
     * @param i
     *            the employee
     * 
     * @return The preferred team of the employee i or null if the employee has no team.
     */
    private Team getFirstPreferredTeam() {
        EmployeePreference pref;
        List<Team> teams;
        if ((pref = pb.preferences.get(i)) == null || (teams = pref.getPreferredTeam()) == null || teams.size() <= 0) {
            return null;
        }
        return teams.get(0);
    }

    @Override
    protected boolean runSolver() throws GeneratePlanifException {
        // Check if the employee can be assigned to preferred team.
        return (new CheckPreferredTeam(pb, i, j).run());
    }

    @Override
    protected boolean setUp() throws GeneratePlanifException {
        /*
         * Verify if the employee has a valid preferred team.
         */
        this.originalBound = BoundSnapshot.create(pb.variablesForEmployee(i));
        // Apply the non-availabilities
        pb.fixNonAvailabilitiesVariables(i);
        // extract conditions to be reused unfeasible
        // Check if has pref
        Team team = getFirstPreferredTeam();
        if (team == null) {
            this.feasible = false;
            return false;
        }
        // check if production
        if ((j = pb.table.indexOf(team)) <= -1) {
            this.feasible = false;
            return false;
        }
        LOGGER.info("Employee " + pb.employeeToString(i) + " preferential seniority being considered.");
        return true;
    }

    @Override
    protected void unfeasible() throws GeneratePlanifException {
        Team team = getFirstPreferredTeam();
        if (team == null) {
            if (!pb.monitor.callbackContinue(new PreferedSeniorityWithoutPrefTeamCallbackReason(employee))) {
                // Throw new exception.
                throw new GeneratePlanifException("cancel by user", GeneratePlanifException.CANCEL_BY_USER);
            }
        } else if (!pb.monitor.callbackContinue(new PreferedSeniorityCallbackReason(employee, team))) {
            // Throw new exception.
            throw new GeneratePlanifException("cancel by user", GeneratePlanifException.CANCEL_BY_USER);
        }
        // Restore the variable bounds
        this.originalBound.restore();
        // Adds the constraint saying that an employee with preferred seniority has to work at least once in the
        // planif
        Linear linear = pb.lp.createLinear();
        for (int j2 = 0; j2 < pb.xijk[i].length; j2++) {
            for (int k = 0; k < pb.xijk[i][j2].length; k++) {
                if (pb.xijk[i][j2][k] != null) {
                    linear.add(pb.lp.createTerm(ONE, pb.xijk[i][j2][k]));
                }
            }
        }
        String name = String.format("SUM from{j} to{m} SUM from{k} to {p} xijk >= 1, for i=%d", i);
        pb.lp.addConstraint(name, linear, ONE, null);
        this.feasible = true;
        LOGGER.info("Employee {} can't be assigned to his prefered team but has to work.", pb.employeeToString(i));
    }
}