/**
 * 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.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.hibernate.criterion.Criterion;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Property;
import org.hibernate.criterion.Restrictions;

import com.patrikdufresne.managers.AbstractManager;
import com.patrikdufresne.managers.ManagerContext;
import com.patrikdufresne.managers.ManagerException;
import com.patrikdufresne.managers.Query;
import com.patrikdufresne.util.BidiMultiHashMap;
import com.patrikdufresne.util.BidiMultiMap;
import com.planimod.core.planif.GeneratePlanifContext;

/**
 * Manager providing functions to manipulate the Task object.
 * 
 * @author Patrik Dufresne
 * 
 */
public class TaskManager extends AbstractManager<Task> {

    /**
     * Create a time range criterion.
     * 
     * @param start
     *            the start time
     * @param end
     *            the end time
     * @return the Criterion.
     */
    private static Criterion startEndCriterion(Date start, Date end) {
        // (start < event.start < end)
        // OU
        // (start < event.end < end)
        // OU
        // (event.start < start ET event.end > end)
        return Restrictions
                .or(
                        Restrictions
                                .or(
                                        Restrictions.between(AbstractCalendarEvent.START_DATE, start, end),
                                        Restrictions.between(AbstractCalendarEvent.END_DATE, start, end)),
                        Restrictions.and(Restrictions.lt(AbstractCalendarEvent.START_DATE, start), Restrictions.gt(AbstractCalendarEvent.END_DATE, end)));
    }

    public TaskManager(PlanimodManagers managers) {
        super(managers);
    }

    /**
     * Create a new instance of GeneratePlanifContext that may be used to compute the result of a planif.
     * 
     * @throws ManagerException
     */
    public GeneratePlanifContext createGeneratePlanifContext() throws ManagerException {

        return new GeneratePlanifContext(getManagers());

    }

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

    /**
     * Create a map to represent the qualification of the employees for a set of tasks.
     * <p>
     * The table include only not-archived employee.
     * 
     * @param start
     *            the start time
     * @param end
     *            the end time
     * @return the map
     * @throws ManagerException
     */
    public TaskQualificationTable getQualificationTable(final Date start, final Date end) throws ManagerException {
        return getManagers().query(new Query<TaskQualificationTable>() {

            @Override
            public TaskQualificationTable run() throws ManagerException {

                Set<Task> tasks = new HashSet<Task>();
                Set<Position> positions = new HashSet<Position>();
                for (Task t : list(start, end)) {
                    tasks.add(t);
                    positions.add(t.getPosition());
                }

                BidiMultiMap<Employee, Position> table = getManagers().getQualificationManager().getQualificationTableByPositions(positions);

                return new TaskQualificationTable(table, tasks);

            }
        });
    }

    /**
     * Create a map to represent the availability of the employee for a set of tasks. This map contains an entry if an
     * employee is not available for a task.
     * 
     * @param start
     *            the start time
     * @param end
     *            the end time
     * @return the map or empty map if their isn't non-availabilities
     * 
     * @throws ManagerException
     */
    public TaskNonAvailabilityTable getNonAvailabilityTable(final Date start, final Date end) throws ManagerException {
        return getManagers().query(new Query<TaskNonAvailabilityTable>() {

            @Override
            public TaskNonAvailabilityTable run() throws ManagerException {

                Collection<NonAvailability> nonAvailabilities = getManagers().getNonAvailabilityManager().list(start, end);

                return new TaskNonAvailabilityTable(nonAvailabilities, list(start, end));

            }
        });
    }

    /**
     * List planif events for the given planif calendar entry.
     * 
     * @param planif
     *            the planif calendar
     * @return list of planif event
     * 
     * @throws ManagerException
     */
    public List<Task> list(final Date start, final Date end) throws ManagerException {
        return getManagers().query(new Query<List<Task>>() {
            @Override
            public List<Task> run() throws ManagerException {
                return ManagerContext.getDefaultSession().createCriteria(Task.class).add(startEndCriterion(start, end)).list();
            }
        });
    }

    public List<Task> listByEmployee(final Date start, final Date end, final Employee employee) throws ManagerException {
        return getManagers().query(new Query<List<Task>>() {
            @Override
            public List<Task> run() throws ManagerException {
                return ManagerContext
                        .getDefaultSession()
                        .createCriteria(Task.class)
                        .add(startEndCriterion(start, end))
                        .add(Restrictions.eq(Task.EMPLOYEE, employee))
                        .list();
            }
        });
    }

    public List<Task> listByProductionEvents(final Collection<? extends ProductionEvent> events) throws ManagerException {
        return getManagers().query(new Query<List<Task>>() {
            @Override
            public List<Task> run() throws ManagerException {
                return ManagerContext.getDefaultSession().createCriteria(Task.class).add(Restrictions.in(Task.PRODUCTION_EVENT, events)).list();
            }
        });
    }

    /**
     * Return a table of product position.
     * 
     * @param events
     * 
     * @return
     * @throws ManagerException
     */
    public BidiMultiMap<Product, ProductPosition> listProductPositionTable(final Collection<ProductionEvent> events) throws ManagerException {
        return getManagers().query(new Query<BidiMultiMap<Product, ProductPosition>>() {

            @Override
            public BidiMultiMap<Product, ProductPosition> run() throws ManagerException {
                if (events.size() == 0) {
                    return new BidiMultiHashMap<Product, ProductPosition>();
                }
                // FIXME the list of events should be used to reduce the
                // size of the table Query database
                DetachedCriteria subSelectProducts = DetachedCriteria.forClass(ProductionEvent.class).setProjection(Property.forName(ProductionEvent.PRODUCT));
                List<ProductPosition> productPositions = ManagerContext
                        .getDefaultSession()
                        .createCriteria(ProductPosition.class)
                        .add(Property.forName(ProductPosition.PRODUCT).in(subSelectProducts))
                        .list();

                // Create the table.
                BidiMultiMap<Product, ProductPosition> table = new BidiMultiHashMap<Product, ProductPosition>();
                for (ProductPosition pp : productPositions) {
                    table.put(pp.getProduct(), pp);
                }
                return table;
            }

        });

    }

    @Override
    public Class<Task> objectClass() {
        return Task.class;
    }

}
