Shoes.app(:title => "Timer", :height => 140, :width => 230, :resizeable => false) do
  background "#548898".."#3d6976"
    
  stack :margin => 10 do
    @timer = title "00:00:00", :align => "center", :stroke => "#a0b8be"
  end
    
  flow :margin => 10 do
    button "Start" do
      
      # if no pause time is set, use the current time
      if @pause_time.nil?
        @time = Time.now
      
      # otherwise set the pause interval and unpause flag
      else 
        @unpause = true
        if @pause_interval
           @pause_interval = @pause_interval + (Time.now - @pause_time)
        else
          @pause_interval = Time.now - @pause_time
        end
      end
   
     # not stopped or paused now
      @stop = nil
      @pause = nil
      @pause_time = nil
    end
    
    # set pause flag and pause time
    button "Pause" do
      @pause = true
      @pause_time = Time.now            
    end    
    
    # set stop flag and reset
    button "Stop" do
      @stop = true
      @pause_time = nil
      @pause_interval = 0
    end
  end
  
  def format_time(seconds)
    seconds = seconds.round
    return [seconds/3600, seconds/60 % 60, seconds % 60].map{|t| t.to_s.rjust(2,'0')}.join(':')
  end
     
  animate(1) do

    # show the current time minus the start time
    if @pause_interval
      @timer.replace format_time(Time.now - @time - @pause_interval) unless @stop || @pause || @unpause          
    else
      @timer.replace format_time(Time.now - @time) unless @stop || @pause || @unpause            
    end
    
    if @unpause
      @timer.replace format_time(Time.now - @time - @pause_interval)
      @unpause = nil
    end
  end 
end