#
# SudokuBoard class
#                2009/11/29  by Hidetoshi NAGAI (nagai@ai.kyutech.ac.jp)
#
require 'tk'

class SudokuBoard < TkWindow
  include TkComposite

  VAL_CHAR = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ'

  def _create_block_frame
    TkFrame.new(@frame, :borderwidth=>2, :relief=>:ridge)
  end

  def _keycheck(c)
    begin
      if (idx = VAL_CHAR.index(c = c.upcase)) && 
          @base <= idx && idx < @max + @base
        c
      else
        nil
      end
    rescue
      nil
    end
  end

  def _create_cell(frame)
    fnt = @font
    lbl = TkLabel.new(frame, :width=>2, :bd=>1, :relief=>:sunken, 
                      :anchor=>:e, :highlightthickness=>1) {
      @font = fnt
      @fix  = false
      self.font = @font[1]
    }

    def lbl.fix(mode)
      @fix = ((mode)? true: false)
      self.font = @font[(mode)? 0: 1]
    end
    def lbl.fix?
      @fix
    end

    lbl.bind('Enter', proc{lbl.focus})
    lbl.bind('BackSpace', proc{lbl.text = '' unless lbl.fix?})
    lbl.bind('Delete', proc{lbl.text = '' unless lbl.fix?})
    lbl.bind('KeyPress', '%A'){|c|
      lbl.text = c if !lbl.fix? && !c.empty? && c = _keycheck(c)
    }
  end

  def _cursor_bind(win, x, y)
    win.bind('Up', proc{@cells[y - 1][x].focus}) if y > 0
    win.bind('Down', proc{@cells[y + 1][x].focus}) if y < @max - 1
    win.bind('Left', proc{@cells[y][x - 1].focus}) if x > 0
    win.bind('Right', proc{@cells[y][x + 1].focus}) if x < @max - 1
  end

  def _create_block(block_x, block_y)
    f = ((@frames[block_x] ||= [])[block_y] ||= _create_block_frame)

    @size.times{|y|
      coord_y = @size * block_y + y
      board_line = @cells[coord_y] ||= []
      row = []
      @size.times{|x|
        coord_x = @size * block_x + x
        cell = (board_line[coord_x] = _create_cell(f))
        _cursor_bind(cell, coord_x, coord_y)
        row << cell
      }
      Tk.grid(*(row << {:sticky=>'news'}))
    }

    f
  end
  private :_create_block_frame, :_keycheck, :_create_cell, 
          :_cursor_bind, :_create_block

  def initialize_composite(keys={})
    @frames = []
    @cells = []
    @init = nil

    @font = []
    @font[0] = TkFont.new(keys['font'] || 'Helvetica -12')
    @font[1] = TkFont.create_copy(@font[0]).weight(:bold)

    @size = (keys['size'] || 3)
    @base = (keys['base'] || ((@size > 3)? 0: 1))
    @max = @size ** 2

    if @max > VAL_CHAR.length
      fail ArgumentError, "table-size == #{@size} is too large"
    end

    @size.times{|y|
      @size.times{|x|
        _create_block(x, y).grid(:row=>y, :column=>x)
      }
    }

    delegate('DEFAULT', *(@cells.flatten))

    @cells[0][0].focus
  end

  def set(x, y, val)
    return self if @cells[y][x].fix?
    if val.nil?
      @cells[y][x].text = ''
    elsif @base <= val && val < @max + @base
      @cells[y][x].text = VAL_CHAR[val, 1]
    else
      fail ArgumentError, "invalid value: #{val}"
    end
    self
  end

  def erase(x, y)
    @cells[y][x].text = ''
    @cells[y][x].foreground = 'black'
    @cells[y][x].fix(false)
    self
  end

  def clear
    @max.times{|y|
      @max.times{|x|
        erase(x, y)
      }
    }
    self
  end

  def init(ary = nil)
    ary = @init unless ary
    return clear unless ary

    init_ary = []

    ary.each_with_index{|row, y|
      init_ary << row.dup
      row.each_with_index{|val, x|
        @cells[y][x].fix(false)
        set(x, y, val)
        @cells[y][x].fix((val)? true: false)
      }
    }

    @init = init_ary
    self
  end

  def _check_row(y)
    vals = []
    @max.times{|x|
      vals << @cells[y][x].text
    }
    vals.sort.join('') == VAL_CHAR[@base, @max]
  end

  def _check_column(x)
    vals = []
    @max.times{|y|
      vals << @cells[y][x].text
    }
    vals.sort.join('') == VAL_CHAR[@base, @max]
  end

  def _check_block(block_x, block_y)
    vals = []
    @size.times{|y|
      @size.times{|x|
        vals << @cells[@size * block_y + y][@size * block_x + x].text
      }
    }
    vals.sort.join('') == VAL_CHAR[@base, @max]
  end

  def check
    @size.times{|block_y|
      @size.times{|block_x|
        return false unless _check_block(block_x, block_y)
      }
    }

    @max.times{|idx|
      return false unless _check_column(idx) && _check_row(idx)
    }

    true
  end

  def get_errors
    errors = []

    @size.times{|block_y|
      @size.times{|block_x|
        errors << [block_x, block_y] unless _check_block(block_x, block_y)
      }
    }

    @max.times{|idx|
      errors << [:column, idx] unless _check_column(idx)
    }

    @max.times{|idx|
      errors << [:row, idx] unless _check_row(idx)
    }

    errors
  end
end

if __FILE__ == $0
=begin
  tbl = SudokuBoard.new(:size=>2).pack
  tbl.init([
             [1,2,3,4],
             [3,4,1,2],
             [2,1,4,3],
             [4,3,2,1]
           ])
=end
=begin
  tbl = SudokuBoard.new(:size=>2, :base=>0).pack
  tbl.init([
             [0,1,2,3],
             [2,3,0,1],
             [1,0,3,2],
             [3,2,1,0]
           ])
=end
#  SudokuBoard.new(:size=>2, :base=>0).pack.set(2,1,2).set(2,2,0).erase(2,1)
#  SudokuBoard.new(:size=>2).pack.set(2,1,3).set(2,2,1).erase(2,1)
#  SudokuBoard.new(:size=>3).pack
  parent = Tk.root

  tables = []

  tbl3 = SudokuBoard.new(parent, :size=>3).pack
  tbl3.init([
     [5, 3, nil, nil, 7, nil, nil, nil, nil],
     [6, nil, nil, 1, 9, 5, nil, nil, nil],
     [nil, 9, 8, nil, nil, nil, nil, 6, nil],

     [8, nil, nil, nil, 6, nil, nil, nil, 3],
     [4, nil, nil, 8, nil, 3, nil, nil, 1],
     [7, nil, nil, nil, 2, nil, nil, nil, 6],

     [nil, 6, nil, nil, nil, nil, 2, 8, nil],
     [nil, nil, nil, 4, 1, 9, nil, nil, 5],
     [nil, nil, nil, nil, 8, nil, nil, 7, 9],
  ])

#  tables << tbl3

  tbl4 = SudokuBoard.new(parent, :size=>4).pack
  tbl4.init([
     [nil, 0, 3, nil, 2, 9, 14, 6, 1, 13, 10, 7, nil, 4, 12, nil],
     [8, 6, 9, 10, nil, 3, 4, nil, 2, nil, nil, 14, 0, 13, 1, 5],
     [2, 12, 15, 7, 11, nil, nil, 8, nil, 4, 5, nil, 14, 3, 6, 10],
     [nil, 4, 14, nil, 10, 5, 12, 0, nil, 3, 15, 6, nil, 2, 9, nil], 

     [3, nil, nil, 2, 7, 1, 11, 4, nil, 15, 8, nil, 9, nil, nil, 6], 
     [14, nil, nil, 4, 12, nil, nil, nil, 9, 10, 13, 11, nil, 5, 8, nil], 
     [1, nil,nil, 12, nil, 8, nil, 9, 6, nil, nil, 5, nil, 11, 0, nil], 
     [6, 11, 8, 9, 0, 15, 5, 10, nil, 1,4, 12, 2, nil, nil, 13], 

     [12, nil, nil, 6, 13, 0, 9, nil, 3, 8, 7, 15, 4, 10, 5, 14], 
     [nil, 7, 13, nil, 3, nil, nil, 12, 5, nil, 14, nil, 1, nil, nil, 11], 
     [nil, 8, 11, nil, 1, 14, 7 , 15, nil, nil, nil, 10, 12, nil, nil, 2], 
     [15, nil, nil, 14, nil, 2, 8, nil, 12, 11, 1, 13, 3, nil, nil, 0], 

     [nil, 1, 12, nil, 6, 11, 2, nil, 10, 5, 0, 4, nil, 15, 14, nil], 
     [0, 14, 6, 15, nil, 12, 10, nil, 11, nil, nil, 3, 5, 1, 4, 8], 
     [9, 5, 4, 11, 8, nil, nil, 14, nil, 6, 12, nil, 10, 0, 2, 3], 
     [nil, 3, 2, nil, 5, 4, 0, 1, 15, 14, 9, 8, nil, 7, 11, nil], 
  ])

  tables << tbl4

  TkFrame.new(parent){|f|
    lbl = TkLabel.new(f, :width=>5).pack(:side=>:right)
    TkButton.new(f, :text=>'check', :padx=>2, :pady=>0, 
                 :command=>proc{
                   lbl.text = tables.inject(true){|st, tbl|
                     # tbl.get_errors
                     st && tbl.check
                   }.inspect
                 }){
      self.font.size = 8
    }.pack(:side=>:right)
    TkButton.new(f, :text=>'init', :padx=>3, :pady=>0, 
                 :command=>proc{tables.each{|tbl| tbl.init}}){
      self.font.size = 8
    }.pack(:side=>:right, :padx=>3)
    TkButton.new(f, :text=>'quit', :padx=>3, :pady=>0, 
                 :command=>proc{exit}) {
      self.font.size = 8
    }.pack(:side=>:right, :padx=>3)
  }.pack(:expand=>false, :fill=>:none, :pady=>1)
  Tk.mainloop
end
