/**
 * 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.ui.views.planif;

import static com.planimod.ui.Localized._;

import java.util.Collection;
import java.util.Iterator;

import org.eclipse.core.databinding.conversion.Converter;

import com.patrikdufresne.util.BidiMultiHashMap;
import com.planimod.core.Employee;
import com.planimod.core.Team;
import com.planimod.core.planif.HasSeniorityToWorkOnPreferedTeamWarning;
import com.planimod.core.planif.ProposedWarning;
import com.planimod.ui.databinding.Converters;
import com.planimod.ui.viewers.EmployeeViewerUtils;

/**
 * Converter to create a string for a collection of warnings.
 * 
 * @author Patrik Dufresne
 * 
 */
public class ProposedWarningsToStringConverter extends Converter {

    private static final Object EMPTY = "";

    // Used to follow grammars rules of separators in different language.
    // Ex: In French, using 3 or more "ou" requires a comma.
    private static final int OR_TO_COMMA = 3;

    /**
     * Appends the name of the employee being treated
     * 
     * @param buf
     *            the StringBuilder used to hold the string
     * @param emp
     *            the employee being treated
     */
    private static void appendEmployeeName(StringBuilder buf, Employee emp, String emps) {
        buf.append(getEmployeeName(emp, emps));
    }

    /**
     * Appends the next employee name that could be bumped. Also appends a separator between the employees names.
     * Appends a different separator for the last employee name
     * 
     * @param hasNext
     *            true if there is at least 1 more team to treat
     * @param emp
     *            the employee that could be bumped
     */
    private static String appendNextBumpedEmployee(boolean hasNext, Employee emp) {
        if (hasNext) {
            return getEmployeeSeparatorComma() + EmployeeViewerUtils.getName(emp);
        }
        return getEmployeeSeparatorOr() + EmployeeViewerUtils.getName(emp);
    }

    /**
     * Appends the separator between 2 teams. Adds a comma there is a grammar rule requiring a minimum of separator
     * before using the comma
     * 
     * @param hasNext
     *            true if there is at least 1 more team to treat
     * @param size
     *            the number of different teams being treated
     */
    private static String appendTeamSeparator(boolean hasNext, int size) {
        String emp = "";
        if (hasNext && size < OR_TO_COMMA) {
            emp = getTeamSeparatorWithoutComma();
        } else if (hasNext) {
            emp = getTeamSeparatorWithComma();
        }
        return emp;
    }

    private static String getEmployeeName(Employee emp, String emps) {
        return _("<b>%s</b> peut être affecté à la place de %s.</p></form>", EmployeeViewerUtils.getName(emp), emps);
    }

    private static String getEmployeeSeparatorComma() {
        return _(", ");
    }

    private static String getEmployeeSeparatorOr() {
        return _(" ou ");
    }

    private static String getTeamName(Team t) {
        return _(" sur l'équipe de <b>%s</b>", Converters.removeFrontNumber().convert(t.getName()));
    }

    private static String getTeamSeparatorWithComma() {
        return _(", ou à la place de");
    }

    private static String getTeamSeparatorWithoutComma() {
        return _(" ou à la place de ");
    }

    private static String getWarningMessage() {
        return _("<form><p>L'employé est affecté par défaut à un poste attitré. Il peut toutefois refuser pour être affecté à son équipe de travail préférée.");
    }

    /**
     * Groups the warnings by class
     * 
     * @param fromObject
     *            the collection given
     * @return a BidiMultiHashMap with the classes as keys and the warnings as values
     */
    private static BidiMultiHashMap<Class<?>, ProposedWarning> groupByClass(Collection<ProposedWarning> fromObject) {
        BidiMultiHashMap<Class<?>, ProposedWarning> tableWarningClass = new BidiMultiHashMap<Class<?>, ProposedWarning>();
        for (ProposedWarning warning : (Collection<ProposedWarning>) fromObject) {
            tableWarningClass.put(warning.getClass(), warning);
        }
        return tableWarningClass;
    }

    /**
     * Groups the warnings by employee
     * 
     * @param coll
     *            the collection of ProposedWarning value of groupByClass
     * @return a BidiMultiHashMap with the Employees as keys and the warnings as values
     */
    private static BidiMultiHashMap<Employee, HasSeniorityToWorkOnPreferedTeamWarning> groupByEmployee(Collection<ProposedWarning> coll) {
        BidiMultiHashMap<Employee, HasSeniorityToWorkOnPreferedTeamWarning> tableEmployee = new BidiMultiHashMap<Employee, HasSeniorityToWorkOnPreferedTeamWarning>();
        for (ProposedWarning warning : coll) {
            tableEmployee.put(warning.getEmployee(), (HasSeniorityToWorkOnPreferedTeamWarning) warning);
        }
        return tableEmployee;
    }

    /**
     * Groups the warnings by team
     * 
     * @param coll
     *            the collection of HasSeniorityToWorkOnPreferedTeamWarning value of groupByTeam
     * @return a BidiMultiHashMap with the teams as keys and the warnings as values
     */
    private static BidiMultiHashMap<Team, HasSeniorityToWorkOnPreferedTeamWarning> groupByTeam(Collection<HasSeniorityToWorkOnPreferedTeamWarning> coll) {
        BidiMultiHashMap<Team, HasSeniorityToWorkOnPreferedTeamWarning> tableTeam = new BidiMultiHashMap<Team, HasSeniorityToWorkOnPreferedTeamWarning>();
        for (HasSeniorityToWorkOnPreferedTeamWarning warning : coll) {
            tableTeam.put(((HasSeniorityToWorkOnPreferedTeamWarning) warning).getBumpTeam(), warning);
        }
        return tableTeam;
    }

    /**
     * Create a new converter.
     */
    public ProposedWarningsToStringConverter() {
        super(Collection.class, String.class);
    }

    /**
     * This implementation convert the warnings collection into one single string.
     */
    @Override
    public Object convert(Object fromObject) {
        if (!(fromObject instanceof Collection) || ((Collection) fromObject).size() == 0) {
            return EMPTY;
        }
        StringBuilder buf = new StringBuilder();
        // Groups the warnings by class
        BidiMultiHashMap<Class<?>, ProposedWarning> tableWarningClass = groupByClass((Collection<ProposedWarning>) fromObject);
        // Loops on the warnings classes
        for (Class<?> c : tableWarningClass.keySet()) {
            // Groups the warnings by Employee
            BidiMultiHashMap<Employee, HasSeniorityToWorkOnPreferedTeamWarning> tableEmployee = groupByEmployee(tableWarningClass.valueSet(c));
            // Loops on the employees
            for (Employee e : tableEmployee.keySet()) {
                // Groups the warnings by Team
                BidiMultiHashMap<Team, HasSeniorityToWorkOnPreferedTeamWarning> tableTeam = groupByTeam(tableEmployee.valueSet(e));
                // Hold the string used for an employee
                StringBuilder emps = new StringBuilder();
                // Appends the message related to the warning type
                buf.append(getWarningMessage());
                Iterator<Team> iterTeam = tableTeam.keySet().iterator();
                // Iterates on the different team the employee could be assigned
                while (iterTeam.hasNext()) {
                    Team t = iterTeam.next();
                    Iterator<HasSeniorityToWorkOnPreferedTeamWarning> iterWarning = tableTeam.valueSet(t).iterator();
                    // If the collection of warning is empty it is skipped
                    if (!iterWarning.hasNext()) {
                        continue;
                    }
                    HasSeniorityToWorkOnPreferedTeamWarning warning = iterWarning.next();
                    // Appends the first employee that the employee being treated could bump
                    emps.append(EmployeeViewerUtils.getName(warning.getBumpEmployee()));
                    // Appends the other employees that could be bumped by the employee being treated
                    // Also appends the right separator between the employees
                    while (iterWarning.hasNext()) {
                        warning = iterWarning.next();
                        emps.append(appendNextBumpedEmployee(iterWarning.hasNext(), warning.getBumpEmployee()));
                    }
                    // Appends the name of the team on which the employee could be reassigned
                    emps.append(getTeamName(t));
                    // Appends the right separator between the teams if needed
                    emps.append(appendTeamSeparator(iterTeam.hasNext(), tableTeam.keySet().size()));
                }
                // Appends the name of the employee being treated with the string associated to it
                appendEmployeeName(buf, e, emps.toString());
            }
        }
        return buf.toString();
    }
}