/* object OBJID_GD_PILL */

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <unistd.h>
#include <errno.h>
#include "obj-gd_pill.h"

unsigned int objnew_GD_PILL(void *, int, int);

static void f_free(void *, void *);
static void f_draw(void *, struct VG_Object *);


/* export-function to create a new object-instance of OBJID_GD_PILL
 * @param vgame  private structure of the game
 * @param xm  x-position (centered)
 * @param ym  y-position (centered)
 * @return  instance-ID or 0 = error
 */
unsigned int
objnew_GD_PILL(void *vgame, int xm, int ym)
{
  const int coll_percent = 70;
  struct s_game *sgame = (struct s_game *)vgame;
  struct VG_Object *objp;
  struct sobj_gd_pill *objvars;

  if (sgame == NULL) { return 0; }

  /* create private struct */

  objvars = calloc(1, sizeof(*objvars));
  if (objvars == NULL) { return 0; }

  /* load sprite */
  objvars->sprt = vg4->sprite->load("files/images/goody/pill/pill.sprite");
  if (objvars->sprt == NULL) { f_free(vgame, objvars); return 0; }

  vg4->sprite->imagesize(objvars->sprt, "avg", &objvars->rect.w, &objvars->rect.h);

  objvars->rect.x = xm - objvars->rect.w / 2;
  objvars->rect.y = ym - objvars->rect.h / 2;

  /* create object-instance */
  objp = vg4->object->create(OBJID_GD_PILL, 0, 0, 3, objvars);
  objp->f_free = f_free;
  objp->f_draw = f_draw;

  /* insert object-instance into collision-tag */
  vg4->collision->insert(sgame->coll_tag, objp->instanceid, &objvars->rect, coll_percent);

  return objp->instanceid;
}


/* free private struct of object-instance, called from vg4->object->destroy() */
static void
f_free(void *vgame, void *opriv)
{
  struct sobj_gd_pill *objvars = (struct sobj_gd_pill *)opriv;

  (void)vgame;

  /* free private struct */
  if (objvars->sprt != NULL) { vg4->sprite->destroy(objvars->sprt); }
  free(objvars);
}


/* draw object-instance, called from vg4->object->call_draw() */
static void
f_draw(void *vgame, struct VG_Object *objp)
{
  struct s_game *sgame = (struct s_game *)vgame;
  struct sobj_gd_pill *objvars = (struct sobj_gd_pill *)objp->opriv;
  struct VG_Image *imgp;
  struct VG_ImagecopyAttr iattr;
  struct VG_Position posi;

  if (sgame == NULL) { return; }

  imgp = NULL;
  VG_IMAGECOPY_ATTR_DEFAULT(&iattr);

  vg4->sprite->next(objvars->sprt, &imgp, &iattr);

  if (imgp != NULL) {
    vg4->misc->rect2position(&posi, &objvars->rect);
    posi = vg4->misc->bgposition_getobj(posi);
    vg4->window->copy(imgp, &posi, &iattr);
  }
}
