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

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

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

/**
 * Class used to manage the shift objects.
 */
public class ShiftManager extends AbstractManager<Shift> {
    public ShiftManager(PlanimodManagers managers) {
        super(managers);
    }

    /**
     * This function is used to copy a given collection of calendar events.
     * 
     * @param shifts
     *            The shifts to be copied.
     * @param destWeek
     *            Define the destination week.
     * @param overwrite
     *            True to overwrite the destination
     * @throws ManagerException
     */
    public Map<Shift, Shift> copy(final Collection<Shift> shifts, final Date destWeek, final boolean overwrite) throws ManagerException {
        return getManagers().query(new Query<Map<Shift, Shift>>() {
            @Override
            public Map<Shift, Shift> run() throws ManagerException {
                /*
                 * Check if the destination week is empty.
                 */
                int firstDayOfWeek = getManagers().getApplicationSettingManager().getFirstDayOfWeek();
                Date weekStart = TimeRanges.getWeekStart(destWeek, firstDayOfWeek);
                Date weekEnd = TimeRanges.getWeekEnd(destWeek, firstDayOfWeek);
                List<Shift> existingShifts = list(weekStart, weekEnd);
                if (existingShifts.size() > 0) {
                    if (!overwrite) {
                        throw new ManagerException("Destination week is not empty.");
                    }
                    // Remove existing
                    remove(existingShifts);
                }

                /*
                 * Copy the events
                 */
                Map<Shift, Shift> map = new HashMap<Shift, Shift>();
                for (Shift event : shifts) {
                    // Proceed with a copy
                    Shift newShift = new Shift();
                    newShift.setTeam(event.getTeam());
                    newShift.setStartDate(TimeRanges.getWeekReflexion(event.getStartDate(), destWeek, firstDayOfWeek));
                    newShift.setEndDate(TimeRanges.getWeekReflexion(event.getEndDate(), destWeek, firstDayOfWeek));
                    map.put(event, newShift);
                }
                add(map.values());
                return map;
            }
        });
    }

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

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

    /**
     * List production events in a planif.
     * 
     * @param planifValue
     * @return
     * @throws ManagerException
     */
    public List<? extends AbstractCalendarEvent> listByTeam(final Team team, final Date start, final Date end) throws ManagerException {
        return getManagers().query(new Query<List<? extends AbstractCalendarEvent>>() {
            @Override
            public List<? extends AbstractCalendarEvent> run() throws ManagerException {
                return ManagerContext
                        .getDefaultSession()
                        .createCriteria(objectClass())
                        .add(Restrictions.and(Restrictions.eq(Shift.TEAM, team), startEndCriterion(start, end)))
                        .list();
            }
        });
    }

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

    /**
     * This implementation check the starting and ending date value.
     */
    @Override
    protected void preAddObject(Shift t) throws ManagerException {
        if (t.getStartDate() != null && t.getEndDate() != null && t.getStartDate().compareTo(t.getEndDate()) > 0) {
            throw new IntegrityException("start > end");
        }
        // Check date precision
        Calendar cal = Calendar.getInstance();
        cal.setTime(t.getStartDate());
        if (cal.get(Calendar.MILLISECOND) != 0 || cal.get(Calendar.SECOND) != 0) {
            throw new IntegrityException("startDate too precise");
        }
        cal.setTime(t.getEndDate());
        if (cal.get(Calendar.MILLISECOND) != 0 || cal.get(Calendar.SECOND) != 0) {
            throw new IntegrityException("endDate too precise");
        }
    }

    /**
     * This implementation check the starting and ending date value.
     */
    @Override
    protected void preUpdateObject(Shift t) throws ManagerException {
        if (t.getStartDate() != null && t.getEndDate() != null && t.getStartDate().compareTo(t.getEndDate()) > 0) {
            throw new IntegrityException("start > end");
        }
        // Check date precision
        Calendar cal = Calendar.getInstance();
        cal.setTime(t.getStartDate());
        if (cal.get(Calendar.MILLISECOND) != 0 || cal.get(Calendar.SECOND) != 0) {
            throw new IntegrityException("startDate too precise");
        }
        cal.setTime(t.getEndDate());
        if (cal.get(Calendar.MILLISECOND) != 0 || cal.get(Calendar.SECOND) != 0) {
            throw new IntegrityException("endDate too precise");
        }
    }

    /**
     * Create a time range criterion.
     * 
     * @param start
     *            the start time
     * @param end
     *            the end time
     * @return the Criterion.
     */
    protected 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)));
    }

    /**
     * This implementation override the default behavior by also removing any related tasks.
     * 
     * @param s
     *            list of production event to remove
     * 
     * @throws ManagerException
     */
    @Override
    protected void preRemoveObjects(Collection<? extends Shift> s) throws ManagerException {
        // Load the given shifts into the session, otherwise the production
        // event will reference a different object.
        for (Shift t : s) {
            ManagerContext.getDefaultSession().refresh(t);
        }

        // Remove the associated object
        List<ProductionEvent> events = getManagers().getProductionEventManager().listByShifts(s);
        if (events != null && events.size() > 0) {
            getManagers().getProductionEventManager().remove(events);
        }
    }

}
