require 'ncurses'
require 'forwardable'

module Ncurses
  def self.ncinit &block
    raise ArgumentError, "no block!" unless block_given?
    begin
      module_eval &block
    ensure # make sure everything goes back to normal
      echo
      nocbreak
      nl
      endwin
    end
  end

  def self.add_pair f, b, title=nil
    @pairs ||= {}
    @current_pair ||= 1
    init_pair @current_pair, f, b
    title ||= @current_pair
    @pairs[title] = COLOR_PAIR(@current_pair)
    @current_pair += 1
    title
  end

  def self.use_pair *args
    title, win = args.reverse
    win ||= stdscr
    pair = @pairs[title]
    pair ||= title.kind_of?(Integer) ? title : 0
    win.attron pair
  end

  extend Forwardable
  def_delegators :stdscr, :puts, :print

  class WINDOW
    def puts_bicolor str, pair1, pair2, percent
      y, x = getyx
      use_pair pair1
      str = str.ljust(Ncurses.COLS)
      puts str
      move y, x
      use_pair pair2
      puts str[0, Ncurses.COLS * percent]
    end

    def puts *args
      str, y, x = args.reverse
      y, x = getyx y, x
      print *args
      move y + 1, x
    end
    def print *args
      str, y, x = args.reverse
      move *getyx(y, x) if x or y
      waddstr str.to_s
    end

    #alias old_getyx getyx
    def getyx y=nil, x=nil
      xx, yy = [], []
      Ncurses.getyx self, yy, xx
      y ||= yy.first
      x ||= xx.first
      [y, x]
    end

    class << self
      def self.new *args, &block
        n = super *args
        n.instance_eval &block if block_given?
      end
    end
  end
end
