#include "magnet.h"
#include "ball.h"
#include "graphics.h"
#include <vector>
#include <iostream>
using namespace std;

static unsigned int magnetbmp;
static bool magnetbmpassigned;

extern vector<ball> ballz;

magnet::magnet(floatpoint newcenter)
{
  center = newcenter;
}

void magnet::update(float amount)
{
  vector<ball>::iterator i;
  
  for (i = ballz.begin(); i < ballz.end(); i++)
    {
      floatpoint oldvelocity;
      oldvelocity = i->getvelocity();
      float distance = (i->getcenter() - center).magval();
      float acceleration;
	acceleration  = amount / distance / distance / i->getmass() * 1000;
      floatpoint acc = (center - i->getcenter()) / distance * acceleration;
      i->setvelocity(i->getvelocity() + acc);
      i->setvelocity(i->getvelocity() / 
		     i->getvelocity().magval() * oldvelocity.magval());
    }

}


magnetpair::magnetpair()
{
  timetolive = 0;
}

magnetpair::magnetpair(square * borders, point center, char direction, float lifespan)
{
  timetolive = lifespan;
  if (direction == 'v')
    {
      magnets[0].center.x = center.x;
      magnets[1].center.x = center.x;
      magnets[0].center.y = borders->topy;
      magnets[1].center.y = borders->bottomy;
    }
  if (direction == 'h')
    {
      magnets[0].center.y = center.y;
      magnets[1].center.y = center.y;
      magnets[0].center.x = borders->leftx;
      magnets[1].center.x = borders->rightx;
    }
}

void magnetpair::display()
{
  if (timetolive <= 0)
    return;
  if (magnetbmpassigned == 0)
    {
      magnetbmp = load_bmp("magnetstill.bmp");
      magnetbmpassigned = 1;
    }
  int pic;
    pic = magnetbmp;
 
  
  display_bmp(pic, int(magnets[0].center.x) - bmp_size(pic).x / 2,
	      int (magnets[0].center.y) - bmp_size(pic).y / 2); 
  display_bmp(pic, int(magnets[1].center.x) - bmp_size(pic).x / 2,
	      int (magnets[1].center.y) - bmp_size(pic).y / 2); 
}

void magnetpair::update(float amount)
{
  if (timetolive > 0)
    {
      timetolive -= amount;
      magnets[0].update(amount);
      magnets[1].update(amount);
    }
}
