using UnityEngine;
using System.Collections;

public class Weapon : MonoBehaviour {

    public float Range = 1;
    public int FramesToAttack = 20;
    public int FramesToRecover = 10;

    public float FireDamage = 0;
    public float EarthDamage = 0;
    public float WaterDamage = 0;
    public float WindDamage = 0;

    DemonController ParentDemonController;

    void OnDrawGizmosSelected()
    {
        Gizmos.color = new Color(0.8f, 0.4f, 0, 0.5f);
        Gizmos.DrawSphere(transform.position, Range);
    }

    void Start() {
        isAttacking = false;
        ParentDemonController = GetComponentInParent<DemonController>();
    }

    public bool isAttacking { get; private set; }
    int RemainingFramesToAttack;
    int RemainingFramesToRecover;

    IEnumerator attackCoroutine;
    public void doAttack(CharacterData character)
    {
        if (!isAttacking)
        {
            attackCoroutine = attack(character);
            StartCoroutine(attackCoroutine);
        }
    }

    public void stopAttack()
    {
        if (isAttacking && attackCoroutine != null)
        {
            StopCoroutine(attackCoroutine);
            isAttacking = false;
            attackCoroutine = null;
        }
    }

    IEnumerator attack(CharacterData character)
    {
        isAttacking = true;
        RemainingFramesToAttack = FramesToAttack;
        while (RemainingFramesToAttack > 0)
        {
            RemainingFramesToAttack -= 1;
            yield return new WaitForFixedUpdate();
        }

        character.doDamageToChar(FireDamage, EarthDamage, WindDamage, WaterDamage);
        if (ParentDemonController != null) ParentDemonController.Attack();

        RemainingFramesToRecover = FramesToRecover;
        while (RemainingFramesToRecover > 0)
        {
            RemainingFramesToRecover -= 1;
            yield return new WaitForFixedUpdate();
        }
        isAttacking = false;
    }

    public void incDamage(DamageType type, float amount)
    {
        switch (type)
        {
            case DamageType.Fire: FireDamage += amount; break;
            case DamageType.Earth: EarthDamage += amount; break;
            case DamageType.Water: WaterDamage += amount; break;
            case DamageType.Wind: WindDamage += amount; break;
        }
    }
}
