#! ruby -Ks
# ap-list:2700
# ap-dev:2144

require 'phi'
require "Win32API"
require "lang/SimpleGetText"

def find_window( class_name,caption )
  Win32API.new('user32', 'FindWindow', "PP", "N").Call(class_name, caption.dup)
end

MY_CAPTION   = ARGV.shift || "Please run 'copy_data.rb'."

if /^(\D*)(\d)$/ =~ MY_CAPTION 
  CAPTION_BASE = $1
  APP_NO = $2.to_i
else
##  CAPTION_BASE = MY_CAPTION
##  APP_NO = 5
  raise "Please run 'copy_data.rb'."._
end

@receivers = []
9.times{|n|
  @receivers.push "#{CAPTION_BASE}#{n+1}"
}

form = Phi::Form.new :form_test1 , MY_CAPTION
form.top  = Phi::SCREEN.height / 3 * ( (APP_NO-1)/3 )
form.left = Phi::SCREEN.width  / 3 * ( (APP_NO-1)%3 )
form.height += 30

panel_U    = Phi::Panel.new form
memo_M     = Phi::Memo.new( form,"Data to send from %s"._ % MY_CAPTION )  
memo_D     = Phi::Memo.new( form,"Data received"._ )
splitter_1 = Phi::Splitter.new form
panel_U.align    = Phi::AL_TOP
memo_M.align     = Phi::AL_TOP    ; memo_M.top     = panel_U.bottom
splitter_1.align = Phi::AL_TOP    ; splitter_1.top = memo_M.bottom
memo_D.align     = Phi::AL_CLIENT ; memo_D.top     = splitter_1.bottom
memo_M.height = (memo_M.height + memo_D.height) / 3
#
label       = Phi::Label.new(    panel_U, "Receiver"._ ) 
combo_box   = Phi::ComboBox.new( panel_U )
button      = Phi::Button.new(   panel_U, "Send"._ )  
button_quit = Phi::Button.new(   panel_U, "QUIT"._ )  
combo_box.left   = label.right
button.left      = combo_box.right
button_quit.left = button.right

@receivers.each{|name| combo_box.items.add(name)}

button.on_click = proc{
  receiver_caption = combo_box.text
  if receiver_caption.empty?
    memo_D.lines.text = "No receiver was selected"._
    break
  end
  receiver_handle = find_window( nil , receiver_caption )
  if receiver_handle == 0
    memo_D.text = ("Cannot find receiver form (%s)"._ % receiver_caption)
    break
  end
  form.copy_data(receiver_handle, "send from #{MY_CAPTION}\n on #{Time.now.to_s}\n----\n#{memo_M.text}")
}
button_quit.on_click = proc{
  @receivers.each{|name|
    receiver_caption = name
    if receiver_caption.empty?
      memo_D.lines.text = "No receiver was selected"._
      next
    end
    receiver_handle = find_window( nil , receiver_caption )
    if receiver_handle == 0
      memo_D.text = ("Cannot find receiver form (%s)"._ % receiver_caption)
      next
    end
    form.copy_data(receiver_handle, "QUIT")
  }
}

form.on_copy_data = proc do |sender, handle, data|
  memo_D.lines.text = "received :\n sender's handle = #{handle};\n data = #{data}\n"
  if data == "QUIT"
    limit = Phi::DateTime.now.inc_sec(2)
    Phi::APPLICATION.process_messages  while limit > Phi::DateTime.now
    form.close
  end
end

form.show
Phi.mainloop


