/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package view.tool.timeFields;

import java.util.Calendar;
import javax.swing.JLabel;

/**
 *
 * @author alexis
 */
public class TimeLabel extends JLabel implements Runnable{
    /**
	 * 
	 */
	private static final long serialVersionUID = -7657333453175532311L;
	private static Calendar cal;
    
    /**
     * constructor
     * @param _cal
     * @param isAutoIncrement
     */
    public TimeLabel(Calendar _cal,boolean isAutoIncrement){
        cal = _cal;
        updateTime();
        if(isAutoIncrement)
            new Thread(this).start();
    }
    
    /**
     * update the time
     */
    private void updateTime(){
        String hour = "" + cal.get(Calendar.HOUR_OF_DAY);
        String min = "" + cal.get(Calendar.MINUTE);
        if(hour.length() == 1)
            hour = "0"+hour;
        if(min.length() == 1)
            min = "0"+min;
        setText(hour + ":" + min);
    }
    
    /**
     * @return TimeLabel with current time
     */
    public static TimeLabel TimeLabelWithCurrentTime(){
        return new TimeLabel(Calendar.getInstance(),false);
    }
    
    /**
     * @param _cal
     * @return TimeLabel with specific time
     */
    public static TimeLabel TimeLabelWithTime(Calendar _cal){
        return new TimeLabel(_cal,false);
    }
    
    /**
     * @return TimeLabel with current time and auto increment
     */
    public static TimeLabel TimeLabelWithAutoIncrementCurrentTime(){
        return new TimeLabel(Calendar.getInstance(),true);
    }
    
    /**
     * @param _cal
     * @return TimeLabel with specific time and auto increment
     */
    public static TimeLabel TimeLabelWithAutoIncrementTime(Calendar _cal){
        return new TimeLabel(_cal,true);
    }
    
    /**
     * get calendar
     * @return Calendar
     */
    public Calendar getCalendar(){
        return cal;
    }
    
    /**
     * set calendar
     * @param _cal
     */
    public void setCalendar(Calendar _cal){
        cal = _cal;
        updateTime();
    }

    @Override
    public void run() 
    {
        try
        {
          while (true)
          {
            Thread.sleep(60000);
            if(cal.get(Calendar.MINUTE) == 59)
            {
                cal.add(Calendar.HOUR_OF_DAY, 1);
                cal.set(Calendar.MINUTE, 0);
            }
            else
                cal.add(Calendar.MINUTE, 1);
            updateTime();
          }
       }
       catch(Exception ex)
       {
         ex.printStackTrace();
       }   
    }
}