require 'tk'
require 'drb/drb'
require 'parsedate'
require 'reminder'

class EntryView
  def initialize(parent, title, value='')
    @root = TkFrame.new(parent)
    @label = TkLabel.new(@root) 

    @label.text(title)
    @label.pack('side'=>'left')

    @entry = TkEntry.new(@root)
    @entry.value = value
    @entry.pack('side'=>'left', 'expand'=>true, 'fill'=>'x')
  end
  attr :root

  def value
    @entry.value
  end

  def value=(v)
    @entry.value = v
  end
end

class ReminderView
  def initialize(parent, reminder, user)
    @root = TkFrame.new(parent)
    @reminder = reminder
    @user = user

    @board = TkLabel.new(@root)
    @delete = TkButton.new(@root) do
      text('delete')
    end
    @add = TkButton.new(@root) do
      text('add')
    end

    @list = TkListbox.new(@root)
    @scroll = TkScrollbar.new(@root)

    @board.text user

    @delete.command do |arg|
      delete
    end

    @add.command do |arg|
      add
    end

    @scroll.command do |arg|
      @list.yview *arg
    end

    @list.yscrollcommand do |arg| 
      @scroll.set *arg
    end
     
    @list.bind('Double-Button') do
      @list.curselection.each do |item|
	p @ary[item]
	prepare_entry(@ary[item]['text'], @ary[item]['time']) 
      end
    end

    @delete.pack('side'=>'bottom')
    @add.pack('side'=>'bottom')
    @text_entry = EntryView.new(@root, '¤¤¤Ä')
    @text_entry.root.pack('side'=>'bottom')
    @time_entry = EntryView.new(@root, '¤Ê¤Ë')
    @time_entry.root.pack('side'=>'bottom')

    @board.pack('side'=>'top')
    @list.pack('side' => 'left', 'fill' => 'both', 'expand'=>true)
    @scroll.pack('side' => 'right', 'fill' => 'y')

    @root.pack('fill'=>'both', 'expand'=> true)
    update_list
    prepare_entry
  end

  def update_list
    @list.delete(0, 'end')
    @ary = @reminder.fetch_hash(@user)
    @ary.each do |i|
      str = "#{i['time'].strftime('%Y-%m-%d %H:%M')}: #{i['text']}"
      @list.insert('end', str)
    end
  end

  def delete
    @list.curselection.each do |item|
      p [:delete, @ary[item]]
      @reminder.remove(@user, @ary[item]['key'])
    end
    update_list
  end

  def add
    time = @time_entry.value
    text = @text_entry.value
    time = Time.local(*(ParseDate.parsedate(time)[0,6])) if time
    puts [time, text]
    @reminder.add(text, @user, time)
    update_list
    prepare_entry
  end

  def prepare_entry(text = '', time = Time.now)
    @time_entry.value = time.strftime('%Y-%m-%d %H:%M')
    @text_entry.value = text
  end
end

reminder = Reminder.instance
user = ARGV.shift
view = ReminderView.new(nil, reminder, user)

Tk.mainloop


