using UnityEngine;
using ScrambleKit.Extensions;

namespace ScrambleKit.Move
{
    public class Aimable : MonoBehaviour
    {
        private MoveInputSource input;

        public bool FlipFacingLeft = true;

        private Vector3 normScale;
        private Vector3 flipScale;

        void Start()
        {
            input = transform.root.GetComponent<MoveInputSource>();
            normScale = transform.localScale;
            flipScale = new Vector3(-normScale.x, normScale.y, normScale.z);
        }

        void FixedUpdate()
        {
            FaceTowardAim();
            if(FlipFacingLeft)
                CheckFlip();
        }

        private void FaceTowardAim()
        {
            float aimangle = ((Vector2)transform.position).AngleTo(input.AimingAt);
            transform.eulerAngles = new Vector3(0, 0, aimangle);
        }

        private void CheckFlip()
        {
            if ((transform.localEulerAngles.z+360)%360 > 180)
                transform.localScale = normScale;
            else
                transform.localScale = flipScale;
        }

    }
}
