package performa.utils;

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


public class MessagingUtils 
{
    private static final Random         rand        =   new Random();
    
    public static int WORK_START_HOUR   =   9;
    public static int WORK_STOP_HOUR    =   17;
    
    public static int randInt(int min, int max) 
    {
        return rand.nextInt((max - min) + 1) + min;
    }
    
    public static Date getWithinBusinessHours(Calendar cal, TimeZone timeZone) 
    {
        while (!isWorkingDay(cal)) 
        {            
            cal.add(Calendar.DAY_OF_MONTH, 1);
        }
        
        Calendar    calDayStart =   new GregorianCalendar();
        Calendar    calDayEnd   =   new GregorianCalendar();
       
        calDayStart.setTime(cal.getTime());
        calDayEnd.setTime(cal.getTime());
        
        startOfWorkingDay(calDayStart, timeZone);
        endOfWorkingDay(calDayEnd, timeZone);
        
        if(cal.before(calDayStart))
        {
            cal.setTimeZone(timeZone);
            cal.set(GregorianCalendar.HOUR_OF_DAY, WORK_START_HOUR);
        }
        else if(cal.after(calDayEnd))
        {
            cal.setTimeZone(timeZone);
            cal.add(Calendar.DAY_OF_MONTH, 1);
            cal.set(GregorianCalendar.HOUR_OF_DAY, WORK_START_HOUR);
            
            while (!isWorkingDay(cal)) 
            {            
                cal.add(Calendar.DAY_OF_MONTH, 1);
            }
        }
            
        return cal.getTime();

    }
    
    public static void startOfWorkingDay(Calendar cal, TimeZone timeZone)
    {
        cal.setTimeZone(timeZone);
        cal.set(GregorianCalendar.MILLISECOND, 0);
        cal.set(GregorianCalendar.SECOND, 0);
        cal.set(GregorianCalendar.MINUTE, 0);
        cal.set(GregorianCalendar.HOUR_OF_DAY, WORK_START_HOUR);
    }
    
    public static void endOfWorkingDay(Calendar cal, TimeZone timeZone)
    {
        cal.setTimeZone(timeZone);
        cal.set(GregorianCalendar.MILLISECOND, 0);
        cal.set(GregorianCalendar.SECOND, 0);
        cal.set(GregorianCalendar.MINUTE, 0);
        cal.set(GregorianCalendar.HOUR_OF_DAY, WORK_STOP_HOUR);
    }
    
    public static boolean isWorkingDay(Calendar day)
    {
        int     dayOfWeek = day.get(Calendar.DAY_OF_WEEK);

        return !(dayOfWeek == Calendar.SATURDAY || dayOfWeek == Calendar.SUNDAY);
    }
}