=begin
= WebUnit::Table/TableRow/TableCell/NilTableCell
  Copyright(C) 2001 yuichi TAKAHASHI
  $Id: table.rb,v 1.1.1.1 2003/01/21 11:50:40 yuichi Exp $
=end

module WebUnit

  class Table < HtmlElem

    attr_reader :rows

    def initialize( ah )
      super( 'table', ah )
      @rows = []
    end

    def add_row( ah )
      @rows.push( TableRow::new( ah ) )
    end

    def add_cell( cell )
      p = @rows.last.size + 1
      if @rows.size > 1 && @rows[-2].at(p) && @rows[-2].at(p).rs > 1 then
        @rows.last.add( @rows[-2].at(p) )
        @rows[-2].at(p).rs -= 1
      end
      @rows.last.add( cell )
      while cell.cs > 1 do
        @rows.last.add( cell )
        cell.cs -= 1
      end
    end

=begin
--- Table#at(r,c=nil)
      return a TableCell, when two arguments(row,col) specified.
      return a TableRow, when a argument(row) specified.
      r and c is both beginning from 1.
=end

    def at( r, c=nil )
      if r < 1
        raise ArgumentError
      end
      if c == nil
        if @rows == [] || @rows.size < r
          raise
        end
        @rows[r-1]
      else
        if c < 1
          raise ArgumentError
        end
        if @rows == [] || @rows.size < r || @rows[r-1].size < c
          NilTableCell::new
        else
          @rows[r-1].at(c)
        end
      end
    end

=begin
--- Table#row_index( data, col=1 )
=end

    def row_index( data, col=1 )
      row = nil
      (1..@rows.size).each do |row|
        break unless self.at(row,col).search( data ) == []
      end
      row
    end

=begin
--- Table#col_index( data, row=1 )
=end
    def col_index( data, row=1 )
      col = nil
      (1..(self.at(row).size)).each do |col|
        break unless self.at(row,col).search( data ) == []
      end
      col
    end

  end

  class TableRow < HtmlElem

    def initialize( ah )
      super( 'tr', ah )
      @cols = []
    end

=begin
--- TableRow#size
      return column number.
=end

    def size
      @cols.size
    end

    def add( col )
      @cols << col
    end

=begin
--- TableRow#at( c )
      return TableCell, pointed by ((|c|)).
      c is beginning from 1.
=end

    def at( c )
      @cols[c-1]
    end

  end

  class TableCell < HtmlElem

    attr_reader :data, :colspan, :rowspan

    attr_accessor :cs, :rs

    def initialize( tag, ah )
      super
      @colspan = ah['colspan']
      @rowspan = ah['rowspan']
      @cs = @colspan.to_i || 1
      @rs = @rowspan.to_i || 1
    end

  end

  class NilTableCell < TableCell

    def initialize
      super( 'dummy', {} )
    end

    def data
      nil
    end

  end

end
