/*
    Bazoo_worms the game
    Copyright (C) 2011  Pavel Prochazka

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/

#include "MG_lib.h"
#include "WRMS_include.h"

static SPRITE *arrow = NULL;

static void
arrow_swing (SPRITE * self)
{
  int *ttl = MG_get_key (self, "ttl");

  *ttl -= MG_get_system_dt ();

  if (*ttl <= 0)
    {
      MG_remove_sprite (self);
      arrow = NULL;
      return;
    }

  int *mid_y = MG_get_key (self, "mid_y");
  POINT mid = { self->dest.x + self->dest.w / 2, *mid_y };
  POINT current = sprite_mid (self);

  VECTOR v = vector_from_points (current, mid);
  v.x = 0;
  v.y = (v.y / 1000.0f);

  MG_set_power (self, &v);
}

static void
arrow_destroy (SPRITE * self)
{
  int *ttl = MG_get_key (self, "ttl");
  int *mid_y = MG_get_key (self, "mid_y");

  free (ttl);
  free (mid_y);
}

SPRITE *
WRMS_arrow_set (SPRITE * worm)
{
  if (!worm)
    return NULL;

  if (arrow)
    MG_remove_sprite (arrow);

  arrow = MG_make_sprite (MG_get_img ("arrow.png"), NULL);

  MG_install_callback (arrow, "on_iter", arrow_swing);
  MG_install_callback (arrow, "on_destroy", arrow_destroy);
  MG_set_key (arrow, "ttl", make_int (ARROW_TTL));
  MG_set_key (arrow, "worm", worm);

  sprite_align_mid (arrow, worm);
  MG_move_sprite (arrow, 0, -2 * (worm->dest.h));

  MG_set_key (arrow, "mid_y", make_int (arrow->dest.y + (arrow->dest.h / 2)));
  MG_set_weight (arrow, 100.0f);

  return arrow;
}

SPRITE *
WRMS_arrow_unset ()
{
  if (arrow)
    {
      MG_remove_sprite (arrow);
    }

  arrow = NULL;
  return arrow;
}

void
WRMS_arrow_reset ()
{
  arrow = NULL;
}
