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

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

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

/**
 */
public class NonAvailabilityManager extends AbstractManager<NonAvailability> {
    /**
     * 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 NonAvailabilityManager(PlanimodManagers managers) {
        super(managers);
    }

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

    /**
     * List all non-availabilities for all employee for the given time range.
     * <p>
     * This list does not contrains archived employee.
     * 
     * @throws ManagerException
     */
    public List<NonAvailability> list(final Date start, final Date end) throws ManagerException {
        return getManagers().query(new Query<List<NonAvailability>>() {
            @Override
            public List<NonAvailability> run() throws ManagerException {
                return ManagerContext.getDefaultSession().createCriteria(NonAvailability.class).add(startEndCriterion(start, end)).createCriteria(
                        NonAvailability.EMPLOYEE).add(Restrictions.isNull(ArchivableObject.ARCHIVED_DATE)).list();
            }
        });
    }

    /**
     * List the non-availabilities for the given time range and visibility.
     * 
     * @param start
     *            the start date
     * @param end
     *            the end date
     * @param visibility
     *            True to show visible item.
     * @return list of non-availabilities.
     * @throws ManagerException
     */
    public List<NonAvailability> listByVisibility(final Date start, final Date end, final boolean visibility) throws ManagerException {
        return getManagers().query(new Query<List<NonAvailability>>() {
            @Override
            public List<NonAvailability> run() throws ManagerException {
                return ManagerContext.getDefaultSession().createCriteria(NonAvailability.class).add(Restrictions.eq(NonAvailability.VISIBLE, visibility)).add(
                        startEndCriterion(start, end)).createCriteria(NonAvailability.EMPLOYEE).add(Restrictions.isNull(ArchivableObject.ARCHIVED_DATE)).list();
            }
        });
    }

    public List<NonAvailability> listByEmployees(final Collection<Employee> employees, final Date start, final Date end) throws ManagerException {
        return getManagers().query(new Query<List<NonAvailability>>() {
            @Override
            public List<NonAvailability> run() throws ManagerException {
                return ManagerContext.getDefaultSession().createCriteria(objectClass()).add(startEndCriterion(start, end)).add(
                        Restrictions.in(NonAvailability.EMPLOYEE, employees)).list();
            }
        });
    }

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

    /**
     * This implementation check the starting and ending date value.
     */
    @Override
    protected void preAddObject(NonAvailability t) throws ManagerException {
        // Check date value
        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(NonAvailability t) throws ManagerException {
        // Check date value
        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");
        }
    }
}
