using Mirror;
using System;
using UnityEngine;

namespace Player
{
    public abstract class Pawn : NetworkBehaviour
    {
        public event Action<Pawn> OnDamage;
        public event Action<Pawn, bool> OnLiveState;
        public int health = 100;
        public bool Alive = true;

        void Start()
        {
            RotationSpeed = PlayerPrefs.GetFloat("Sensitivity");
        }

        [SyncVar]
        public float _speedMul = 1f;

        public void TakeDamage()
        {
            OnDamage?.Invoke(this);
        }

        [Command]
        public void CmdDie()
        {
            RpcDie();
        }

        [ClientRpc]
        public void RpcDie()
        {
            Die();
        }

        public void Die()
        {
            Alive = false;
            OnLiveState?.Invoke(this, Alive);
            // spectator
        }

        public void Live()
        {
            Alive = true;
            OnLiveState?.Invoke(this, Alive);
        }

        public void SetSpeedMul(float mul)
        {
            _speedMul = mul;
        }

        private Vector2 _mouseLook;
        [SyncVar]
        public float _cinemachineTargetPitch;
        private float _rotationVelocity;
        public float RotationSpeed = 1f;
        public float BottomClamp = -90.0f;
        public float TopClamp = 90.0f;
        public GameObject CinemachineCameraTarget;


        public void CameraRotation()
        {
            if (Cursor.lockState == CursorLockMode.None) return;

            _mouseLook = new Vector2(Input.GetAxis("Mouse X"), -Input.GetAxis("Mouse Y"));
            _cinemachineTargetPitch += _mouseLook.y * RotationSpeed;
            _rotationVelocity = _mouseLook.x * RotationSpeed;

            _cinemachineTargetPitch = ClampAngle(_cinemachineTargetPitch, BottomClamp, TopClamp);

            transform.Rotate(Vector3.up * _rotationVelocity);

            CinemachineCameraTarget.transform.localRotation = Quaternion.Euler(_cinemachineTargetPitch, 0.0f, 0.0f);
            // CmdSetCameraPitch(_cinemachineTargetPitch);
        }

        private static float ClampAngle(float lfAngle, float lfMin, float lfMax)
        {
            if (lfAngle < -360f) lfAngle += 360f;
            if (lfAngle > 360f) lfAngle -= 360f;
            return Mathf.Clamp(lfAngle, lfMin, lfMax);
        }
    }
}