using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class EquipmentSword : Equipment {

    [Header("Physics")]
    [SerializeField] Collider dmgCol;
    [SerializeField] PhysicsProxy physProxy;

    public float damage = 1.0f;
    public float colDur = 0.35f;

    [Header("Sounds")]
    [SerializeField] GameSound swingSound;

    Coroutine attackCR;

    private void Awake() {
        physProxy.OnTriggerEnterA = OnTriggerEnter;
    }

    private void OnDestroy() {
        Destroy(physProxy.gameObject);
    }

    public override void Init() {
        physProxy.character = ownerChar;
    }

    public override void Attack() {
        hitted.Clear();
        if(attackCR != null) {
            StopCoroutine(attackCR);
        }
        attackCR = StartCoroutine(AttackIE());
    }

    IEnumerator AttackIE() {
        swingSound.Play();
        dmgCol.enabled = true;
        yield return new WaitForSeconds(colDur);
        dmgCol.enabled = false;

        attackCR = null;
    }

    static IHittable hittable;

    HashSet<IHittable> hitted = new HashSet<IHittable>();

    private void OnTriggerEnter(Collider other) {
        if(other == ownerCol) return;
        
        hittable = other.GetComponent<IHittable>();
        if(hittable != null) {
            if(hitted.Contains(hittable)) return;
            else {
                hittable.Hit(ownerStats.GetMeeleDamage(damage));
                hitted.Add(hittable);
            }
        }
    }
}
