/* object OBJID_OHARD */

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

unsigned int objnew_OHARD(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_OHARD
 * @param vgame   private structure of the game
 * @param xm      x-position (center)
 * @param ym      y-position (center)
 * @return  instance-ID or 0 = error
 */
unsigned int
objnew_OHARD(void *vgame, int xm, int ym)
{
  const int coll_percent = 100;
  struct s_game *sgame = (struct s_game *)vgame;
  struct VG_Object *objp;
  struct sobj_ohard *objvars;
  char pfad[512];
  int i1;

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

  /* create private struct */

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

  /* load image */
  for (i1 = 9; i1 > 0; i1--) {
    snprintf(pfad, sizeof(pfad), "files/images/ohard/%d/ohard%d.bmp", sgame->svdt.dnew.gamelevel + 1, i1);
    if (access(pfad, R_OK) == 0) { break; }
  }
  if (i1 == 0) { fprintf(stderr, "No ohard-image found.\n"); f_free(vgame, objvars); return 0; }
  i1 = ZUFALL(OBJID_OHARD, 1, i1);
  snprintf(pfad, sizeof(pfad), "files/images/ohard/%d/ohard%d.bmp", sgame->svdt.dnew.gamelevel + 1, i1);
  objvars->imgp = vg4->image->load(pfad);
  if (objvars->imgp == NULL) { f_free(vgame, objvars); return 0; }
  snprintf(pfad, sizeof(pfad), "files/images/ohard/%d/ohard%d-dmg.bmp", sgame->svdt.dnew.gamelevel + 1, i1);
  objvars->imgp_dmg = vg4->image->load(pfad);
  if (objvars->imgp_dmg == NULL) { f_free(vgame, objvars); return 0; }

  vg4->image->getsize(objvars->imgp, NULL, &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_OHARD, 0, 0, 2, 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_ohard *objvars = (struct sobj_ohard *)opriv;

  (void)vgame;

  /* free private struct */
  if (objvars->imgp != NULL) { vg4->image->destroy(objvars->imgp); }
  if (objvars->imgp_dmg != NULL) { vg4->image->destroy(objvars->imgp_dmg); }
  free(objvars);
}


/* draw object-instance, called from vg4->object->call_draw() */
static void
f_draw(void *vgame, struct VG_Object *objp)
{
  struct sobj_ohard *objvars = (struct sobj_ohard *)objp->opriv;
  struct VG_Position posi;

  (void)vgame;
  vg4->misc->rect2position(&posi, &objvars->rect);
  posi = vg4->misc->bgposition_getobj(posi);
  vg4->window->copy(objvars->is_damaged ? objvars->imgp_dmg : objvars->imgp, &posi, NULL);
}
