require 'date'
class Calendar < Subtlext::Window
  
  def initialize(geometry)
    super(geometry)
    on :draw, method(:redraw)
  end
  def refresh_date
    @date = DateTime.now.to_date
 end
  def redraw(w)
    clear
    lines = `cal -1 #{@date.month} #{@date.year}`.lines.map(&:rstrip)
    lines.each_index do |l|
      lines[l]=" "+lines[l]+" "
      position=lines[l].index("#{(@date.day>9 ? " " : "  ")}#{@date.day} ")
      if !position.nil?
        self.draw_rect(5+(position/3)*18,2+l*13,15,13)
      end
      self.draw_text(1, 13+l*13, lines[l])
    end
  end

  def next_month
    @date=@date >> 1
  end
  def prev_month
    @date=@date << 1
  end

end


configure :clock_with_calendar do |s|

  s.interval = s.config[:interval]      || 1
  s.format   = s.config[:format_string] || "%H:%M:%S"
  s.icon     = Subtlext::Icon.new("clock_with_calendar.xbm")
  geom = Subtlext::Screen.current.geometry

  s.calendar = Calendar.new({ x: s.config[:start_x] || geom.width-135, y: s.config[:start_y] || 14, width: 134, height: 110 }) 
  s.calendar.background = Subtlext::Subtle.colors[:sublets_bg]
  s.calendar.foreground = Subtlext::Subtle.colors[:sublets_fg]
  s.calendar.font="xft:terminus-8"
end 

on :run do |s| 
  s.data = s.icon + Time.now().strftime(s.format)
end

on :mouse_down do |s, x, y, button|
  if button == 1
    if s.calendar.hidden?
      s.calendar.refresh_date
      s.calendar.show
    else
      s.calendar.hide
    end
    return
  end
  if !s.calendar.hidden?
    if button == 4
      s.calendar.prev_month
    elsif button == 5
      s.calendar.next_month
    end

    s.calendar.redraw(s.calendar)
  end
end 
