using System.Collections.Generic;
using UnityEngine;

namespace InterfaceOff.WorldScene
{
    [System.Serializable] public struct PlayerFrameInfo
    {
        public Vector3 Position;
        public Vector2 Rotation;
        public bool ShootGun;
        public int FrameIndex;
    }

    [System.Serializable] public struct PlayerFrameInfoArray
    {
        public PlayerFrameInfo[] FrameInfo;
    }

    public class DevPlayerController : MonoBehaviour
    {
        private CharacterController Controller;
        public float PlayerSpeed = 5f;
        public float CamSens = 2.5f;
        public Transform CameraPivot;

        private float MousePitch;
        private float MouseYaw = 90;
        private int CurrentFrameIndex;

        private List<PlayerFrameInfo> FrameInfo = new();

        private void Awake()
        {
            Controller = GetComponent<CharacterController>();
            
            Cursor.lockState = CursorLockMode.Locked;
            Cursor.visible = false;
        }

        private void OnDestroy()
        {
            PlayerFrameInfoArray arr = new()
            {
                FrameInfo = FrameInfo.ToArray()
            };
            
            string json = JsonUtility.ToJson(arr, prettyPrint: true);
            System.IO.File.WriteAllText(Application.persistentDataPath + "/playerframe.json", json);
            
            Debug.Log("Dumped");
        }
        
        private void FixedUpdate()
        {
            PlayerFrameInfo current = new()
            {
                Position = transform.position,
                Rotation = new Vector2(MousePitch, MouseYaw),
                ShootGun = Input.GetMouseButton(0),
                FrameIndex = CurrentFrameIndex
            };
            
            FrameInfo.Add(current);
            CurrentFrameIndex++;
        }

        private void Update()
        {
            /* Player movement */
            float mouseX = Input.GetAxisRaw("Mouse X") * CamSens * 100f * Time.deltaTime;
            float mouseY = Input.GetAxisRaw("Mouse Y") * CamSens * 100f * Time.deltaTime;

            MouseYaw += mouseX;
            transform.rotation = Quaternion.Euler(0f, MouseYaw, 0f);

            MousePitch -= mouseY;
            MousePitch = Mathf.Clamp(MousePitch, -85f, 85f);
            CameraPivot.localRotation = Quaternion.Euler(MousePitch, 0f, 0f);
            
            /* WASD movement */
            float x = Input.GetAxis("Horizontal");
            float z = Input.GetAxis("Vertical");
            
            Vector3 move = transform.right * x + transform.forward * z;
            Controller.Move(Time.deltaTime * PlayerSpeed * move.normalized);
        }
    }
}
