require 'drb/drb'
require 'singleton'

class ThemeChooser
  include Singleton
  
  THEME_DIR = '/home/mas/public_html/tdiary-theme'
  THEME_URL = '/~seki/tdiary-theme'
  
  def initialize
    @theme_list = collect_theme(THEME_DIR).sort
  end
  attr_reader :theme_list

  def next_theme(theme)
    @theme_list[@theme_list.index(theme) + 1] || theme
  end

  def prev_theme(theme)
    @theme_list[@theme_list.index(theme) - 1] || theme
  end

  def url(theme)
    THEME_URL + "/#{theme}/#{theme}.css"
  end

  private
  def collect_theme(dir_name)
    dir = Dir.open(dir_name)
    dir.find_all do |name|
      case name
      when '.'
	false
      when '..'
	false
      else
	FileTest.directory?(File.join(dir_name, name))
      end
    end
  ensure
    dir.close if dir
  end
end

class ThemeDiv < Div::Div
  set_erb('theme.erb')

  def initialize(session, base)
    super(session)
    @base = base
    @theme = ThemeChooser.instance
    @curr = "clover" #FIXME
    @css = @theme.url(@curr)
  end
  attr_reader :css

  def do_theme(context, params)
    theme, = params['theme']
    return unless theme && theme.length > 0
    return unless @theme.theme_list.include?(theme)
    @curr = theme
    @css = @theme.url(@curr)
  end
end
