#include <iostream.h>
#include <list>
#include "vector.h"
#include "planes.h"

void simStep(list<Plane*>& planes);
printPlanes(list<Plane*> planes);

main()
{
  list<Plane*> allPlanes;
  const int cmdSize=3;
  char cmd[cmdSize];  

  cout << "Enter a command [q: quit, p: new plane, <RET>: step simulator]: ";
  cin.getline(cmd,cmdSize);
  while(strcmp(cmd,"q")!=0) {
    if (strcmp(cmd,"p")==0) {
      allPlanes.push_front(new Plane(cin));
      cin.ignore(100,'\n');
    }
    else {
      simStep(allPlanes);
      printPlanes(allPlanes);
    }
    cout << "Enter a command [q: quit, p: new plane, <RET>: step simulator]: ";
    cin.getline(cmd,cmdSize);
  }
}

// Deleting an item from a list can be tricky
// in the middle of an iteration, since deleting
// the item destroys the iterator object that references it.
// Thus, if you:
//   l.erase(i);
//   i++;
// Incrementing i after erasing it will cause variable
// results, since C++ does not guarantee anything about
// what an iterator references *after* it has bee used in an erase
// (or after an insert, for that matter).
// This function uses a trick that works in all cases:
// - mark the position of the next item (note that this always
//   esists since you cant erase the end iterator)
// - erase the current item
// - set the iterator to the item before the marked one (this
//   is the element that used to be before the item that was erased)
//   so that when it is incremented in the for loop it will point
//   to the correct (next) item.
planeItor removePlane(list<Plane*> planes, planeItor i)
{
  planeItor j;

  cout << "Plane #" << (*i)->getNumber() << " is out of Range.\n";
  j=i;
  j++; // Move j to the next item.
  planes.erase(i);  // delete item i
  i=j; // i was deleted, set it back to something in the list
  i--; // move i back before increment
  return i;
}

// Run one step of the simulation (1 sec)
// may change the list of planes if one goes out of range.
void simStep(list<Plane*>& planes)
{
  planeItor i;

  cout << "=================\n";

  for(i=planes.begin(); i!= planes.end(); i++)
    (*i)->setNextPosition();

  for(i=planes.begin(); i!= planes.end(); i++) {
    (*i)->checkProximity(planes);
    if ((*i)->outOfRange())
      i=removePlane(planes,i);
  }
}

printPlanes(list<Plane*> planes)
{

  constPlaneItor i;

  for(i=planes.begin(); i!= planes.end(); i++)
    cout << *i << endl;
}

  

