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

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;

import org.hibernate.criterion.Restrictions;

import com.patrikdufresne.managers.AbstractManager;
import com.patrikdufresne.managers.ArchivableObject;
import com.patrikdufresne.managers.Exec;
import com.patrikdufresne.managers.ManagerContext;
import com.patrikdufresne.managers.ManagerException;
import com.patrikdufresne.managers.Query;

/**
 * Manage the employee preferences.
 * <p>
 * This manager has a speficif implementation to handle the archivable state of the {@link Employee} object.
 * 
 * @author Patrik Dufresne
 */
public class EmployeePreferenceManager extends AbstractManager<EmployeePreference> {

    /**
     * Create a new manager.
     * 
     * @param managers
     *            parent managers
     */
    public EmployeePreferenceManager(PlanimodManagers managers) {
        super(managers);
    }

    /**
     * Return the managers
     * 
     * @return
     */
    @Override
    public PlanimodManagers getManagers() {
        return (PlanimodManagers) super.getManagers();
    }

    /**
     * Return the employee preference object for the given employee.
     * 
     * @param employee
     *            the employee object
     * @return the employee preference
     * @throws ManagerException
     */
    public EmployeePreference getByEmployee(final Employee employee) throws ManagerException {
        return getManagers().query(new Query<EmployeePreference>() {
            @Override
            public EmployeePreference run() throws ManagerException {
                return (EmployeePreference) ManagerContext.getDefaultSession().createCriteria(objectClass()).add(
                        Restrictions.eq(EmployeePreference.EMPLOYEE, employee)).uniqueResult();
            }

        });
    }

    /**
     * List the preference for the given list of employee.
     * 
     * @param employees
     *            list of employee (may include archived employee)
     * @return list of preferences for the given employees
     * @throws ManagerException
     */
    public List<EmployeePreference> listByEmployees(final Collection<? extends Employee> employees) throws ManagerException {
        return getManagers().query(new Query<List<EmployeePreference>>() {
            @Override
            public List<EmployeePreference> run() throws ManagerException {
                // FIXME This function return multiple EmployeePreference for
                // the same Employee.
                List<EmployeePreference> preferences = ManagerContext.getDefaultSession().createCriteria(objectClass()).add(
                        Restrictions.in(EmployeePreference.EMPLOYEE, employees)).list();
                // Quick fix
                return new ArrayList<EmployeePreference>(new HashSet<EmployeePreference>(preferences));
            }
        });
    }

    /**
     * This implementation return a list of employee preferences.
     * <p>
     * The list does not contains archived employee.
     */
    @Override
    public List<EmployeePreference> list() throws ManagerException {
        return getManagers().query(new Query<List<EmployeePreference>>() {
            @Override
            public List<EmployeePreference> run() throws ManagerException {
                // FIXME This function return multiple EmployeePreference for
                // the same Employee.
                List<EmployeePreference> preferences = ManagerContext.getDefaultSession().createCriteria(EmployeePreference.class).createCriteria(
                        EmployeePreference.EMPLOYEE).add(Restrictions.isNull(ArchivableObject.ARCHIVED_DATE)).list();
                // Quick fix
                return new ArrayList<EmployeePreference>(new HashSet<EmployeePreference>(preferences));
            }
        });
    }

    /**
     * This implementation remove the {@link Employee} and the {@link EmployeePreference} objects
     * 
     * @see com.patrikdufresne.managers.IManager#remove(java.util.Collection)
     */
    @Override
    public void remove(final Collection<? extends EmployeePreference> s) throws ManagerException {
        checkObject(s);
        getManagers().exec(new Exec() {
            @Override
            public void run() throws ManagerException {
                for (EmployeePreference pref : s) {
                    ManagerContext.getDefaultSession().delete(pref);
                    ManagerContext.getDefaultSession().delete(pref.getEmployee());
                }
            }
        });
    }

    /**
     * This implementation always return <code>EmployeePreference.class</code>.
     */
    @Override
    public Class<EmployeePreference> objectClass() {
        return EmployeePreference.class;
    }

    /**
     * Check if the preferred position is classified.
     * 
     * @param t
     *            the object to validate
     * 
     * @throws ManagerException
     *             if the preferred position is not classified
     */
    @Override
    protected void preAddObject(EmployeePreference t) throws ManagerException {
        Position position = t.getPreferredPosition();
        if (position != null) {
            // Check if the position is classified
            if (!position.getClassified()) {
                throw new IntegrityException("preferred position should be classified");
            }
            // Make sure the employee is qualify
            getManagers().getQualificationManager().setQualification(position, t.getEmployee(), true);
        }
    }

    /**
     * This implementation raise an exception in the following case:
     * <ul>
     * <li>If the preferred position is not a classified position.</li>
     * <li>If the associated employee object is archived</li>
     * </ul>
     * 
     * 
     * 
     * @param t
     *            the object to validate
     * 
     * @throws ManagerException
     *             if the preferred position is not classified
     */
    @Override
    protected void preUpdateObject(EmployeePreference t) throws ManagerException {
        super.preUpdateObject(t);
        Position position = t.getPreferredPosition();
        if (position != null) {
            // Check if the position is classified
            if (!position.getClassified()) {
                throw new IntegrityException("preferred position should be classified");
            }
            // Make sure the employee is qualify
            getManagers().getQualificationManager().setQualification(position, t.getEmployee(), true);
        }
        // Check archived state
        if (t.getEmployee().getArchivedDate() != null) {
            throw new ManagerException("can't update an archived record");
        }
    }

}
