// Jason Brillante "Damdoshi"
// Hanged Bunny Studio 2014-2015
//
// KoBang!

#include		<iostream>
#include		<math.h>
#include		"kobang.hpp"

static double		 Polar(double			a,
			       double			b)
{
  if (a < 0 && (int)b == 0)
    return (-M_PI);
  return (2 * atan(b / (a + sqrt(a * a + b * b))));
}

void			kobang::event(void)
{
  sf::Event		event;

  while (win.pollEvent(event))
    {
      if (event.type == sf::Event::Closed)
	{
	  win.close();
	  exit(0);
	}
      else if (event.type == sf::Event::KeyPressed)
	{
	  if (event.key.code == sf::Keyboard::Escape)
	    {
	      win.close();
	      exit(0);
	    }
	  else if (event.key.code == sf::Keyboard::Left && started)
	    heropos = (heropos == 0 ? width - 1 : heropos - 1);
	  else if (event.key.code == sf::Keyboard::Right && started)
	    heropos = (heropos == width - 1 ? 0 : heropos + 1);
	  else if (event.key.code == sf::Keyboard::Space && !started)
	    {
	      started = 1;
	      msg = "start!";
	      msg_timer = 20;
	    }
	  /*
	  else if (event.key.code == sf::Keyboard::F1)
	    turn_left();
	  else if (event.key.code == sf::Keyboard::F2)
	    turn_right();
	  else if (event.key.code == sf::Keyboard::F3)
	    set_eye_size(eye_asked_size - 2);
	  else if (event.key.code == sf::Keyboard::F4)
	    set_eye_size(eye_asked_size + 2);
	  else if (event.key.code == sf::Keyboard::F5)
	    startdeforming();
	  else if (event.key.code == sf::Keyboard::F6)
	    stopdeforming();
	  else if (event.key.code == sf::Keyboard::F7)
	    changecolor();
	  else if (event.key.code == sf::Keyboard::F8)
	    changediscotype();
	  else if (event.key.code == sf::Keyboard::F9)
	    backtransparency = backtransparency - 5 < 0 ? 0 : backtransparency - 5;
	  else if (event.key.code == sf::Keyboard::F10)
	    backtransparency = backtransparency + 5 > 255 ? 255 : backtransparency + 5;
	  */
	}
      else if (event.type == sf::Event::MouseWheelMoved && started)
	{
	  if ((heropos += event.mouseWheel.delta) < 0)
	    heropos += width;
	  else if (heropos > width - 1)
	    heropos -= width;
	}
      else if (event.type == sf::Event::MouseButtonPressed)
	{
	  down = 1;
	  if (!started)
	    {
	      started = 1;
	      msg = "start!";
	      msg_timer = 20;
	    }
	}
      else if (event.type == sf::Event::MouseButtonReleased)
	down = 0;
      else if (event.type == sf::Event::MouseMoved && started)
	if (down)
	  {
	    double	coef;
	    double	angle;

	    coef = 360.0 / width;
	    angle = (Polar((double)event.mouseMove.x - win.getSize().x / 2.0,
			   (double)event.mouseMove.y - win.getSize().y / 2.0)
		     * 180.0) / M_PI;
	    if (angle < coef)
	      heropos = ::round(angle / coef);
	    else if ((angle <= 45 && angle > 0) || (angle < -90))
	      heropos = ::round((angle + coef / 2) / coef);
	    else
	      heropos = ::round((angle - coef / 2) / coef);
	    if (heropos < 0)
	      heropos += width;
	  }
    }
}
