package com.visualpatterns.timex.util;

import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;

/**
 * Klasa pomocnicza dla daty.
 * @author anil
 */
public class DateUtil
{
    /**
     * Zwraca date soboty z biezacego tygodnia.
     */
    public static Date getCurrentPeriodEndingDate()
    {
        // powtarzaj az znajdziesz SUNDAY
        GregorianCalendar gc = new GregorianCalendar();
        while (gc.get(GregorianCalendar.DAY_OF_WEEK) != GregorianCalendar.SUNDAY)
            gc.add(GregorianCalendar.DATE, 1);

        return gc.getTime();
    }

    /** 
     * Data poniedzialku biezacego tygodnia 
     */
    public static Date getCurrentPeriodStartingDate()
    {
        // powtrzaj az znajdziesz MONDAY
        GregorianCalendar gc = new GregorianCalendar();
        while (gc.get(GregorianCalendar.DAY_OF_WEEK) != GregorianCalendar.MONDAY)
            gc.add(GregorianCalendar.DATE, -1);

        return gc.getTime();
    }

    /**
     * Zwraca date z wyzerowanymi paramterami
     */
    public static Date getDateWithZeroTime(Date date)
    {
        Calendar modifiedDate = new GregorianCalendar();
        modifiedDate.setTime(date);
        modifiedDate.set(Calendar.HOUR_OF_DAY, 0);
        modifiedDate.set(Calendar.MINUTE, 0);
        modifiedDate.set(Calendar.SECOND, 0);
        modifiedDate.set(Calendar.MILLISECOND, 0);

        return modifiedDate.getTime();
    }

    /**
     * Zwraca date z paramtrami ustawionymi na max
     * dla dnia (that is, 11:59:59.999)
     */
    public static Date getDateWithMaxTime(Date date)
    {
        Calendar modifiedDate = new GregorianCalendar();
        modifiedDate.setTime(date);
        modifiedDate.set(Calendar.HOUR_OF_DAY, 23);
        modifiedDate.set(Calendar.MINUTE, 59);
        modifiedDate.set(Calendar.SECOND, 59);
        modifiedDate.set(Calendar.MILLISECOND, 999);

        return modifiedDate.getTime();
    }

    /**
     * Sprawdza czy checkDate wypada w biezacym tygodniu
     */
    public static boolean isInCurrentPayPeriod(Date checkDate)
    {
        Date weekStartDate = getDateWithZeroTime(getCurrentPeriodStartingDate());
        Date weekEndDate = getDateWithMaxTime(getCurrentPeriodEndingDate());

        return (!checkDate.before(weekStartDate) && !checkDate
                .after(weekEndDate));
    }
}
