using System.IO;
using UnityEngine;

namespace InterfaceOff.WorldScene
{
    public class PlayerController : MonoBehaviour
    {
        private static PlayerController Instance;
        private PlayerFrameInfo[] Frames;
        
        [Header("Bullet Tracer Info")]
        [SerializeField] private LineRenderer BulletTracerRenderer;
        [SerializeField] private Transform BulletTracerStart;
        [SerializeField] private Transform BulletTracerEnd;
        
        [Header("Dev View")]
        [SerializeField] private int FrameIndex;
        
        private float LerpValue;
        
        private void Awake()
        {
            /* Loads the JSON, temporary. TODO: Insert the JSON into this .cs file */
            string json = File.ReadAllText(Application.dataPath + "/Resources/playerframe.json");
            Frames = JsonUtility.FromJson<PlayerFrameInfoArray>(json).FrameInfo;
        }

        private void FixedUpdate()
        {
            /* Iterates the frame index */
            FrameIndex = (FrameIndex + 1) % (Frames.Length - 2);
        }

        private void Update()
        {
            /* Updates the position according to the lerp */
            LerpValue = (LerpValue + Time.deltaTime * 20f) % 1f;
            
            PlayerFrameInfo frameA = Frames[FrameIndex + 0];
            PlayerFrameInfo frameB = Frames[FrameIndex + 1];
            
            transform.position = Vector3.Lerp(frameA.Position, frameB.Position, LerpValue);
            
            Vector2 rotation = Vector2.Lerp(frameA.Rotation, frameB.Rotation, LerpValue);
            transform.rotation = Quaternion.Euler(rotation.x, rotation.y, 0);
            
            /* Updates the gun state */
            BulletTracerRenderer.positionCount = 2;
            BulletTracerRenderer.SetPosition(index: 0, BulletTracerStart.position);
            BulletTracerRenderer.SetPosition(index: 1, BulletTracerEnd.position);

            BulletTracerRenderer.enabled = Frames[FrameIndex].ShootGun;
        }
    }
}