#! ruby

require 'phi' ; include Phi
require 'rdb' ; include RDB
require 'RGUI'

table = Table.new( Database.new('DBDEMOS') , 'biolife.db' ).open
    GC.start
data_source = DataSource.new table

form = Form.new :form
panel = RGUI::Panel.new form
panel.align = AL_BOTTOM
panel.add(
  hbox1 = RGUI::Hbox.new.add(*[
    button_select = Button.new( panel,:button_select, "選択／解除"),
    button_all_o = Button.new( panel,:button_all_o, "全部選択"),
    button_all_x = Button.new( panel,:button_all_x, "全部解除"),
]) )
panel.layout

#    GC.start

grid = DBGrid.new(form, :grid)
grid.align = Phi::AL_CLIENT
grid.font.style = [Phi::FS_BOLD]
grid.default_drawing = false

#    GC.start

grid.data_source = data_source


$selection = {}

sel_all = proc{|sw|
  table.disable_controls{
    table.bookmark{
      table.each{|fields|
        key = fields[0].value
        $selection[key] = sw
      }
    }
  }
  grid.invalidate
}

button_all_o.on_click = proc{ sel_all.call true }
button_all_x.on_click = proc{ sel_all.call false }

button_select.on_click = proc{
  key = table[0].value
  $selection[key] ^= true
  grid.invalidate
}

#    GC.start

def grid.on_draw_column_cell(rect, col, column, state)
  if column.field.data_type == RDB::FT_GRAPHIC
    bmp = Bitmap.new
    bmp.assign column.field
    canvas.stretch_draw rect, bmp
  else
#p $selection
#p self
#p self.data_source
#p self.data_source.data_set
#p self.data_source.data_set.fields
#p self.data_source.data_set.fields.count
#p self.data_source.data_set[0]
#    GC.start
    canvas.brush.color = CL_RED if $selection[ self.data_source.data_set[0].value]
    canvas.text_rect(rect, rect.left, rect.top, column.field.to_s)
  end
  if state.include? Phi::GD_FOCUSED
    canvas.draw_focus_rect(rect)
  end
end

form.show
Phi.mainloop
