package uk.co.patrickhaston.pdharray2d;

import java.util.ArrayList;
//import java.util.Vector;


public class PdhArray2d //extends Vector 
{
  protected int rows = 0;
  protected int cols = 0;
  
  private ArrayList rowData;
  
  public PdhArray2d()
  {
    rowData = new ArrayList();
  }
  
  public PdhArray2d(int nRows, int nCols)
  {
    rowData = new ArrayList(nRows);
    if(nRows>=0 && nCols>=0)
    {
      for(int i=0; i<= nRows; i++)
      {
        rowData.add(new ArrayList(nCols));
      }
    }
    rows = nRows;
    cols = nCols;
  }

  public Object elementAt(int row, int col)
  {
    // test to make sure the row is within bounds
    if(row<0 || row>=rows) return null; 
    // test to make sure there is data at this row
    if(rowData.get(row) == null) return null;
    // as the row to return the data
    return ((ArrayList) rowData.get(row)).get(col);
  }
  
  public void setElementAt(Object obj, int row, int col)
  {
    // test to make sure the row is within bounds
    if(row<0) return;
    // test to see if there are enough rows
    if(row > rows )
    {
      while(rows < row )
      {
        addRow();
      }
    }
    if(col > cols)
    {
      while(cols < col)
      {
        addColumn();
      }
    }
    // test to see if this row has been created
    if(rowData.get(row) == null)
    {
      rowData.set(row, new ArrayList(cols));
    }
    // set the element in the row
    ((ArrayList) rowData.get(row)).set(col, obj);
  }
  
  public void addRow()
  {
    rows++;
    rowData.add(new ArrayList(cols));
  }
  
  public void addColumn()
  {
    cols++;
    for(int i=0; i<=rows; i++)
    {
      ((ArrayList) rowData.get(i)).add(null);
    }
  }
  
  public void insertRow(int row)
  {
    // test to see if there are enough rows
    if(row > rows )
    {
      while(rows < row )
      {
        addRow();
      }
    }
    else
    {
      rowData.add(row, new ArrayList(cols));
      rows++;
    }
  }

  public void insertColumn(int col)
  {
    if(col > cols)
    {
      // add extra columns required to each row
      while(cols < col)
      {
        addColumn();
      }
    }
    else
    {
      for(int i=0; i<=rows; i++)
      {
        ((ArrayList) rowData.get(i)).add(col, null);
      }
      cols++;
    }
  }
}
