package main;

import java.util.Iterator;
import java.util.Random;

public class SpawnPoint {

  static int numSpawnPoints = 0;

  Point loc;
  long lastSpawned;
  long interval;
  Creature creature;
  int numSpawns;
  int maxSpawns;
  int idNum;

  public SpawnPoint(Creature creature, Point loc, long interval, int maxSpawns) {
    this.creature = creature;
    this.loc = loc;
    this.interval = interval;
    this.maxSpawns = maxSpawns;
    this.lastSpawned = 0L;
    this.idNum = ++numSpawnPoints;
  }

  public Creature spawn() {
    if (System.currentTimeMillis() - this.lastSpawned >= this.interval && this.numSpawns < this.maxSpawns) {
      this.lastSpawned = System.currentTimeMillis();
      Creature cr = this.creature.copy();
      Point newLoc = null;
      Random gen = new Random();
      boolean goodLoc = false, occupied = false;
      while (!goodLoc) {
        newLoc = new Point(this.loc.getX() - 400 + gen.nextInt(800), this.loc.getY() - 400 + gen.nextInt(800));
        if (newLoc.getX() >= 0 && newLoc.getY() >= 0 && LostHavenRPG.map.getLoc(newLoc.getX() / 100, newLoc.getY() / 100).isPassable() && Point.dist(newLoc, this.loc) <= 400.0D) {
          occupied = false;
          int xLow = newLoc.getX() / 100 - 2;
          int xHigh = xLow + 5;
          int yLow = newLoc.getY() / 100 - 2;
          int yHigh = yLow + 5;
          if (xLow < 0) {
            xLow = 0;
          }
          if (xHigh > LostHavenRPG.map.getLength()) {
            xHigh = LostHavenRPG.map.getLength();
          }
          if (yLow < 0) {
            yLow = 0;
          }
          if (yHigh > LostHavenRPG.map.getHeight()) {
            yHigh = LostHavenRPG.map.getHeight();
          }
          for (int x = xLow; x < xHigh; x++) {
            for (int y = yLow; y < yHigh; y++) {
              Iterator<Creature> iter = LostHavenRPG.map.getLoc(x, y).getCreatures().iterator();
              while (iter.hasNext() && !occupied) {
                Creature cur = iter.next();
                if (Point.dist(cur.getLoc(), newLoc) < 100.0D) {
                  occupied = true;
                }
              }
            }
          }
          if (!occupied) {
            goodLoc = true;
          }
        }
      }
      cr.setLoc(newLoc);
      cr.setSpawnPoint(this);
      this.numSpawns++;
      return cr;
    }

    return null;
  }

  public CreatureType getType() {
    return this.creature.getType();
  }

  public Point getLoc() {
    return this.loc;
  }

  public void removeCreature() {
    this.numSpawns--;
  }

  public void clear() {
    this.numSpawns = 0;
    this.lastSpawned = 0L;
  }
}
