#include "demon.h"
#include "villager.h"
#include "weapons.h"
#include <stdio.h>
#include <stdlib.h>
#include <stddef.h>
#include <string.h>
#include <sys/types.h>

struct demon *init_demon(enum demon_category category, char name[50], int HP_max, int damage, enum distance range){
    
    struct demon *demon = malloc(sizeof(struct demon));
    if (demon == NULL)  return NULL;

    strcpy(demon->name, name);
    demon->category = category;
    demon->damage = damage * demon->category;
    demon->HP_max = HP_max * demon->category;
    demon->cur_HP = demon->HP_max;
    demon->range = range;

    return demon;
}
void update_demon_hp(struct demon *demon, int amount){
    if (demon == NULL) return;
    demon->cur_HP -= amount;
    if (demon->cur_HP <= 0) printf("You killed the demon %s !!\n", demon->name);

}
void destroy_demon(struct demon *demon){

    if (demon == NULL) return;
    free(demon);
}

void chase(struct demon *demon, struct villager *villager){

    if(demon == NULL || villager == NULL) return;

    if (villager->distance != CLOSE) villager->distance --;
    printf("The demon %s is chasing you.\n",demon->name);
}

void basic_attack(struct demon *demon, struct villager *target){

    if (demon == NULL || target == NULL) return;
    printf("RAAAAAGH! %s attacks you to deal %i damage.\n",demon->name,demon->damage);
    update_villager_hp(target, demon->damage);
}

void draining_attack(struct demon *demon, struct villager *target){

    if(demon == NULL || target == NULL) return;

    //printf("Degats: %i\n", demon->damage);
   //target->cur_HP -= demon->damage;
   int damage = demon->damage/2;
    update_villager_hp(target, damage);
    demon->cur_HP += damage/2;
    printf("SLURRRRP! %s attacks you to deal %i damage and regenerates %i HP.\n", demon->name, damage, damage/2);

}

void heavy_attack(struct demon *demon, struct villager *target){

    if (demon == NULL || target == NULL) return;

    int damage = demon->damage * 2;
    int hits = demon->HP_max * 0.10;
    update_villager_hp(target, damage);
    update_demon_hp(demon, hits);
    printf("BAM! %s attacks you with all his strength to deal %i damage.\n", demon->name, damage);
}

void demon_action(struct demon *demon, struct villager *villager){

    if (demon == NULL || villager == NULL) return;

    if (villager->distance > demon->range) chase(demon, villager);
    else if (demon->cur_HP > demon->HP_max * 0.75) heavy_attack(demon, villager);
    else if (demon->cur_HP < demon->HP_max * 0.25) draining_attack(demon,villager);
    else basic_attack(demon, villager);
}

