require 'phi'
include Phi
require 'rdb'
include RDB

def add(table, id, memo, icon)
  table.append
  table['id'] = id
  table['memo'] = memo
  table['icon'] = Icon.new.load(icon)
  table.post
end

form = Form.new

table = Table.new
table.close
table.table_type = RDB::TT_PARADOX
table.table_name = 'ap'

if not table.exist?
  i = table.field_defs
  i.clear
  i.add 'id'  , RDB::FT_STRING, 10, false
  i.add 'memo', RDB::FT_STRING, 50, false
  i.add 'icon', RDB::FT_GRAPHIC, 0, false
  i = table.index_defs
  i.clear
  i.add '', 'id', [RDB::IX_PRIMARY]
  if table.store_defs
    table.create_table
    table.open
  end
  begin
    table.database.trans_isolation = RDB::TI_DIRTY_READ
    table.database.transaction{
      add table, "apollo",  "Apollo GUI Application", "icon3.ico"
      add table, "ap"     , "Apollo Console Application", "icon1.ico"
      #raise # to rollback all
      #break # to commit only 2 records.
      add table, "runtime", "Apollo for ShortCut", "arima.ico"
    }
  rescue
    p "canceled"
  end
  p "created database"
else
  p "already exists"
end

table = Table.new
table.table_name = 'ap'
table.open

data_source = DataSource.new table

grid = DBGrid.new(form, :grid)
grid.align = Phi::AL_CLIENT
grid.data_source = data_source
grid.default_drawing = false

def grid.on_cell_click(column)
  p column.field
  column.field.data_set.edit
  column.field.data_set['memo'] = '（変更）'
  column.field.data_set.post
  p column.field
end

def grid.on_draw_column_cell(rect, col, column, state)
  canvas.text_rect(rect, rect.left, rect.top, column.field.to_s)
  if column.field.data_type == RDB::FT_GRAPHIC
#    bmp = Bitmap.new
#    bmp.assign column.field
#    canvas.stretch_draw rect, bmp
    icon = Icon.new

#    icon.assign column.field
=begin
TIcon は TGraphicField を assign できない。
TGraphicField は DB Unit で定義されている。
TIcon は TGraphicField の存在を知る由もない。
=end

#    stream = BlobStream.new
#    column.field.save stream
#    icon.load stream
=begin
だから，Stream 経由で渡す。TGraphicField に対応する Stream は
TBlobStream だ。TGraphicField は TBlobField から継承している。
=end

    icon.load BlobStream.new(column.field)
=begin
TBlobStream.Create には引数として TBlobField 型を渡す。
=end
    canvas.stretch_draw rect, icon
=begin
TIcon 型は stretch できないようだ。透明色は有効である。
=end
  end
  if state.include? Phi::GD_FOCUSED
    canvas.draw_focus_rect(rect)
  end
end

form.show
Phi.mainloop
