using UnityEngine;

public class Target : MonoBehaviour
{

  public Vector3 startPosition;
  public Vector3 targetPosition;

  public float moveSpeed = 1.0f;
  public float waitTime = 1.0f;
  private float currentWaitTime = 0f;
  private bool waiting = false;
  public int points = 1;

  private GameManager gameManager;




  // Start is called once before the first execution of Update after the MonoBehaviour is created
  void Start()
  {
    currentWaitTime = 0;
    startPosition = transform.position;
  }

  // Update is called once per frame
  void Update()
  {
    if (waiting)
    {
      Waiting();
    } else
    {
      Moving();

      CheckTargetReached();

    }
  }

  public void SetValue(float moveSpeed, float waitTime, int points, Vector3 targetPosition, GameManager gameManager) {
    this.moveSpeed = moveSpeed;
    this.waitTime = waitTime;
    this.points = points;
    this.targetPosition = targetPosition;
    this.gameManager = gameManager;
  }


  private void CheckTargetReached()
  {
    if (targetPosition == transform.position)
    {
      transform.position = targetPosition;
      targetPosition = startPosition;
      startPosition = transform.position;

      currentWaitTime = 0;
      waiting = true;

    }
  }

  private void Moving()
  {
    Vector3 distanceToTarget = targetPosition - transform.position;
    Vector3 direction = Vector3.Normalize(distanceToTarget);


    Vector3 travel = direction * moveSpeed * Time.deltaTime;

    if (travel.magnitude >= distanceToTarget.magnitude)
    {
      travel = distanceToTarget;
    }



    transform.position = transform.position + travel;
  }



  private void Waiting()
  {
    currentWaitTime += Time.deltaTime;
    if (currentWaitTime > waitTime)
    {
      waiting = false;
    }
  }

  private void OnTriggerEnter(Collider other)
  {
    Destroy(other.gameObject);
    if (gameManager != null)
    {
      gameManager.NotifyTargetDestroyed(this);
    }
  }

}
