#! ruby
# NetMaster's HTTP Component example
# author: YOSHIDA Kazuhiro <moriq@moriq.com>

require 'phi'
include Phi
require 'fastnet/socket'
require 'fastnet/http'
require 'dialogs'
require 'rgui/ui'

form = RGUI::Form.new :form1
form.caption = 'NetMaster\'s HTTP Component example'
form.height = RGUI.min form.height * 2, Phi::SCREEN.height - 64
form.width  = RGUI.min form.width  * 2, Phi::SCREEN.width  - 64

=begin
Edit1: URL 入力
Edit2: 送信クッキー入力
Edit3: ローカル電子メールアドレス入力
Edit4: ローカルプログラム名入力
Edit5: ユーザー ID 入力
Edit6: パスワード入力
Edit7: リダイレクト元入力
Memo1: ヘッダー表示
Memo2: 本体表示
Memo3: 送信ヘッダー（SendHeader）表示
Button1: HTTP Get を実行
=end

edits = [
  Label.new(form, :lbl1, 'url'       ), Edit.new(form, :edit1, 'localhost'),
  Label.new(form, :lbl2, 'cookie'    ), Edit.new(form, :edit2),
  Label.new(form, :lbl3, 'mail_addr' ), Edit.new(form, :edit3),
  Label.new(form, :lbl4, 'prog_name' ), Edit.new(form, :edit4),
  Label.new(form, :lbl5, 'user'      ), Edit.new(form, :edit5),
  Label.new(form, :lbl6, 'passwd'    ), Edit.new(form, :edit6),
  Label.new(form, :lbl7, 'referer'   ), Edit.new(form, :edit7),
]

memos = [
  Memo.new(form, :memo1),
  Memo.new(form, :memo2),
  Memo.new(form, :memo3),
]
def memo_fixed(memo)
  memo.scroll_bars = Phi::SS_VERTICAL
  memo.font.name = 'ＭＳ ゴシック'
end
memos.each { |i| memo_fixed i }

Button.new form, :button1, 'Get'

vbox1 = UI::Vbox.new [edits, form.memo3]
vbox2 = UI::Vbox.new [form.memo1, form.memo2, form.button1], 4, false
hbox1 = UI::Hbox.new [vbox1, vbox2], 8
form.add hbox1

form.layout
form.show

form.on_resize = proc { form.layout }

http = NMHTTP.new

form.button1.on_click = proc do |sender|
  p "on_click"
  http.header_info.mail_addr = form.edit3.text
  http.header_info.prog_name = form.edit4.text
  http.header_info.cookie = form.edit2.text
  http.header_info.referer = form.edit7.text
  http.header_info.user = form.edit5.text
  http.header_info.passwd = form.edit6.text
  http.input_file_mode = true
  http.header = "./head.txt"
  http.body = "./body.txt"
  http.get(form.edit1.text)
end

http.on_about_to_send = proc do |sender|
  p "on_about_to_send"
# http1.send_header["If-Modified-Since"] = "Wed, 09 Sep 1998 10:49:15 GMT"
  form.memo3.text = http.send_header.text
end

http.on_success = proc do |sender, cmd|
  p "on_success #{cmd}"
  case cmd
  when 'get'
#   form.memo1.lines.load("./head.txt")
    form.memo1.text = http.header
    form.memo2.lines.load("./body.txt")
  end
end

http.on_failure = proc do |sender, cmd|
  p "on_failure #{cmd}"
end

Phi.mainloop
