using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using DG.Tweening;

public class SmashingRock : MonoBehaviour {
  public bool Active = true;

  public AudioSource audioSource;
  public float interval;
  public float smashTime;
  public float retractTime;
  public float distance;

  private bool hitting = false;

  public void Start() {
    StartCoroutine(TriggerRoutine());
  }

  private void OnTriggerEnter(Collider other) {
    var playerController = other.GetComponent<PlayerController>();
    if (playerController != null && hitting) {
      playerController.HandleSmashed(this);
    }
    var golem = other.GetComponent<GolemController>();
    if (golem != null && hitting) {
      golem.HandleSmashed(this);
    }
  }

  private IEnumerator TriggerRoutine() {
    var to = transform.position + transform.forward * distance;
    while (Active) {
      hitting = true;
      transform.DOMove(to, smashTime)
        .SetEase(Ease.OutCirc)
        .OnComplete(() => {
          hitting = false;
          audioSource.Play();
          Retract();
        });
      yield return new WaitForSeconds(interval);
    }
  }

  private void Retract() {
    var to = transform.position - transform.forward * distance;
    transform.DOMove(to, retractTime);
  }
}
