module UnicodePlot
  class GridLayout
    DEFAULT_WIDTH = 80

    def initialize(n_rows, n_columns, width: Layout::DEFAULT_WIDTH)
      @n_rows = n_rows
      @n_columns = n_columns
      @width = width
    end

    def [](i, j)
      @plots[i * n_cols + j]
    end

    def []=(i, j, plot)
      @plots[i * n_cols + j] = plot
    end

    def <<(plot)
      @plots << plot
    end

    def render(out)
      buffers = []
      (0 ... n_rows).each do |i|
        (0 ... n_columns).each do |j|
          StringIO.open do |sio|
            def sio.tty?; true; end
            render_cell(sio, i, j)
            sio.close
            buffers << sio.string
          end
        end
      end
    end

    def render_cell(out, i, j)
      plot = self[i, j]
      return unless plot
      plot.width = cell_width
    end
  end

  module_function def grid_layout(n_rows, n_cols, *plots, **kw)
    grid = GridLayout.new(n_rows, n_cols, **kw)
    plots.each do |plot|
      grid << plot
    end
    grid
  end
end
