# $Id: ext_form.rb,v 1.3 2004/04/13 01:48:11 eto Exp $
# Copyright (C) 2003-2004 Kouichirou Eto, All rights reserved.
# This is free software with ABSOLUTELY NO WARRANTY.
# You can redistribute it and/or modify it under the terms of the GNU GPL2.

require 'qwik/wikitext'

module Qwik
  class Plugin
    def form(dest=nil)
      str = yield
      Form.new(self, dest, str, @pagename).xml
    end
  end

  class Form
    def initialize(plugin, arg, str, pagename=nil)
      @plugin, @arg, @str, @pagename = plugin, arg, str, pagename
      @g = Qxhtml.new
    end

    def xml
      lines = @str.split(/\n/)
      t = @g.table(:class=>'form')
      lines.each {|line|
	ar = line.split(/\|/)
	ar.shift
	case ar.length
	when 1
	  t << @g.tr{@g.td(:colspan=>2, :class=>'msg'){ar.shift}}
	when 2
	  tr = @g.tr{@g.td(:class=>'midashi'){ar.shift}}
	  td = @g.td(:class=>'nakami')
	  nakami = ar.shift
	  nakami.sub!(/^\{\{/, '')
	  nakami.sub!(/\}\}$/, '')
	  if nakami =~ /^([^\(\)]+)\((.*)\)$/
	    cmd, args = $1, $2
	    aa = args.split(/,/)
	    case cmd
	    when 'input'
	      td << @g.text(*aa)
	    when 'select'
	      td << @g.select(*aa)
	    when 'textarea'
	      name, w, h, msg = aa
	      msg = '' if !msg
	      msg.gsub!(/\\n/, "\n")
	      td << @g.textarea(name, w, h){msg}
	    when 'submit'
	      su = @g.submit(*aa)
	      su.attr(:class=>'submit')
	      td << su
	    when 'show'
	      td << @g.span(){@plugin.show(*aa)}
	    when 'ring_show'
	      td << @g.span(){@plugin.ring_show(*aa)}
	    when 'member_user'
	      td << @g.span(){@plugin.member_user(*aa)}
	    end
	  else
	    td << @g.span{nakami}
	  end
	  tr << td
	  t << tr
	else
	  t << @g.tr{ar.to_s} #debug
	end
      }
      @g.div(:class=>'form'){
	action = @pagename.to_s.escape+".html"
	action = @arg.to_s.escape+".html" if @arg && @arg != ''
	@g.form(:method=>'POST', :action=>action){[
	    @g.hidden('page', @pagename.escape),
	    t
	  ]}
      }
    end
  end
end
