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

public class FindTarget : CachedMonoBehaviour
{

    [SerializeField] private Transform target;

    [SerializeField] private SetTarget _setTarget;
    public SetTarget setTarget {
        get {
            if(_setTarget == null) {
                _setTarget = GetComponent<SetTarget>();
            }
            return _setTarget;
        }
    }

    [SerializeField] private int interval = 1;
    private float nextTime = 0;

    // Update is called once per frame
    void Update()
    {
        if(Time.time >= nextTime) {
            nextTime += interval;
            FindClosestPlayer();
        }
    }


    void FindClosestPlayer()
    {
        Transform newTarget = target;
        float distance = Mathf.Infinity;
        if (newTarget != null) {
            distance = Vector3.Distance(transform.position, target.position);
        }
        foreach(Transform potentialTarget in PlayerTarget.targets) {
            float tempDistance = Vector3.Distance(transform.position, potentialTarget.position);
            if (tempDistance < distance) {
                newTarget = potentialTarget;
                distance = tempDistance;
            }
        }
        NewTarget(newTarget);
    }

    void NewTarget(Transform newTarget)
    {
        if (newTarget == null) {
            return;
        }
        target = newTarget;
        setTarget.SetProcessorTarget(target.gameObject);
    }
}
