package uk.co.patrickhaston.mars;

import uk.co.patrickhaston.pdhdata.PdhError;

import java.awt.Point;

public class MarsRegions extends MarsArray 
{
  public MarsRegions(MarsModel model)
  {
    super(model);
    this.CollectionName = "[Regions]";
  }
  
  public void readData(String line)
  {
    int idx = readIndex(line);
    if (idx>0)
    {
      MarsRegion r = new MarsRegion(line);

      this.setElementAt(r, idx);
    }
  }
  
  public void create()
  {
    MarsRegion r = null;
    
    for(int e=0; e<36; e++)
    {
      for (int n=-9; n<9; n++)
      {
        int id = getId(e,n);
        if (id > 0)
        {
          r = new MarsRegion(id);
          r.setLatitude((n+0.5)*10);
          r.setLongitude((e+0.5)*10);
          setElementAt(r, id);
        }
      }
    }
  }
  
  private int getId(int east, int north)
  {
    if (east < 0 || east >35 || north < -9 || north > 8)  
    {
      theModel.logError("MarsRegions.getId(" + east + "," + north +") out of range." );
      return PdhError.OUT_OF_RANGE;
    }
    return (east*18 + north+9 + 1);
  }
  
  private Point getPoint(int id)
  {
    if (id <1 || id > 36*18) return null;
    Point p = new Point();
    p.x = (int) ((id - 1) / 18);
    p.y = id - (p.x * 18) - 9 - 1;
    return p;
  }
  
  public int getId(LatLong location)
  {
    return getId((int) location.east / 10, (int) location.north / 10);
  }
  
  public int getId(double east, double north)
  {
    return getId((int) east / 10, (int) north / 10);
  }
  
  public double getWindspeed(int id)
  {
    if (id <1 || id > 36*18) return PdhError.OUT_OF_RANGE;
    if (id > this.size()) return PdhError.OUT_OF_RANGE;
    return ((MarsRegion) this.get(id)).getWindspeed();
  }

  public double getMaxAirTemp(int id)
  {
    if (id <1 || id > 36*18) return PdhError.OUT_OF_RANGE;
    if (id > this.size()) return PdhError.OUT_OF_RANGE;
    return ((MarsRegion) this.get(id)).getMaxAirTemp();
  }
  
  public int getBiotope(LatLong location)
  {
    if(location == null)
    {
      theModel.logError("MarsRegions.getBiotope(location) - location is null." );
      return PdhError.NULL_VALUE;
    }
    int id = getId(location);
    if (id > 0) return ((MarsRegion) this.get(id)).getBiotope();
    theModel.logError("MarsRegions.getBiotope(location) - Error no " + id );
    return id; // this is an error message
  }
  
  public void update()
  {
    MarsRegion r = null;
    
    for(int e=0; e<36; e++)
    {
      for (int n=-9; n<9; n++)
      {
        int id = getId(e,n);
        if (id > 0)
        {
          r = (MarsRegion) this.get(id);
          if ( r != null )
          {
            r.update(theModel);
          }
        }
      }
    }
  }
}
