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

public class IKLookAt : MonoBehaviour {

	[SerializeField] bool _enabled;
	[SerializeField] Transform _lookAtTarget;
	[SerializeField] Vector3 _lookAtOffset;
	[SerializeField] Animator _animator;
	float _lookWeight = 0;

	void Reset(){
		if(_animator == null) _animator = GetComponent<Animator>();
	}

	void OnAnimatorIK() {
		if(_lookAtTarget != null) {
			_animator.SetLookAtPosition(_lookAtTarget.position + _lookAtOffset);
		}

		_lookWeight = Mathf.Lerp(_lookWeight, (!enabled || _lookAtTarget == null) ? 0 : 1, Time.deltaTime * 2);
		_animator.SetLookAtWeight(_lookWeight);
	}

	public void DisableFor(float time){
		enabled = false;
		CancelInvoke();
		Invoke("EnableAgain", time);
	}

	void EnableAgain(){
		_enabled = true;
	}

	public void SetTarget(Transform target, Vector3 offset){
		_lookAtTarget = target;
		_lookAtOffset = offset;
	}
}
