using System.Collections;
using UnityEngine;
using UnityEngine.Animations;

[RequireComponent(typeof(ThirdPersonCharacter))]
public class FiremanControl : MonoBehaviour
{
    private ThirdPersonCharacter m_Character; //ThirdPersonCharacter的对象的引用
    private Vector3 m_CamForward;  //当前相机的正前方
    public Transform ThirdPersonCamera;//主摄像机的位置           
    private Vector3 m_Move;//根据相机的正前方和用户的输入,计算世界坐标相关的移动方向
    private bool m_Jump;                      

    private Animator animator; 
    public bool driving;
    public bool _getInCar;
    public GameObject currCar;
    public GameObject carCamPoint;
    public CapsuleCollider capsuleCollider;

    private Vector3 InitialPosition;
    private ConstraintSource source;

    private void Start()
    {
        m_Character = GetComponent<ThirdPersonCharacter>();
        animator = GetComponent<Animator>();
        capsuleCollider = GetComponent<CapsuleCollider>();
        InitialPosition = transform.position;
    }


    private void Update()
    {
        if (!m_Jump)
        {
            m_Jump = Input.GetButtonDown("Jump");
        }

        var ahead = this.transform.forward;
        var rayStart = new Vector3(this.transform.position.x, this.transform.position.y + 1f, this.transform.position.z);
        var ray = new Ray(rayStart, ahead);
        if (Physics.Raycast(ray, out RaycastHit hit, 0.7f))
        {
            Debug.DrawLine(ray.origin, hit.point);
            {
                if (hit.transform.gameObject.CompareTag(("Car")) && driving == false)
                {
                    currCar = hit.transform.gameObject;
                    if (currCar != null && !driving)
                    {
                        if (Input.GetKeyDown(KeyCode.E))
                        {
                            _getInCar = true;
                            StartCoroutine(GetInCar());
                        }
                    }
                }
            }
        }

        if (driving)
        {
            if (Input.GetKeyDown(KeyCode.E))
            {
                driving = false;
                _getInCar = false;
                StartCoroutine(GetOutCar());
            }
        }
        else
        {
            if (Input.GetKeyDown(KeyCode.R)) ResetplayerPosition();
        }
    }


    // Fixed update is called in sync with physics
    private void FixedUpdate()
    {
        animator.SetBool("GetInCar", _getInCar);
        if (!driving)
        {
            // read inputs
            float h = Input.GetAxis("Horizontal");
            float v = Input.GetAxis("Vertical");
            m_Character.Input.x = h;
            m_Character.Input.z = v;
            bool crouch = Input.GetKey(KeyCode.C);
            if (ThirdPersonCamera != null)
            {
                m_CamForward = Vector3.Scale(ThirdPersonCamera.forward, new Vector3(1, 0, 1)).normalized;
                m_Move = v * m_CamForward + h * ThirdPersonCamera.right;
            }
            else
            {
                m_Move = v * Vector3.forward + h * Vector3.right;
            }

            // walk speed multiplier
            if (Input.GetKey(KeyCode.LeftShift)) m_Move *= 0.5f;
            // pass all parameters to the character control script
            m_Character.Move(m_Move , crouch, m_Jump);
            m_Jump = false;
        }
        
    }
    /// <summary>
    /// 上车
    /// </summary>
    /// <returns></returns>
    private IEnumerator GetInCar()
    {
        capsuleCollider.enabled = false;
        this.GetComponent<ParentConstraint>().constraintActive = true;
        GetComponent<Rigidbody>().useGravity = false;
        GameObject sitPoint = currCar.transform.Find("sitPoint").gameObject;
        carCamPoint = currCar.transform.Find("carCamPoint").gameObject;
        currCar.GetComponent<CarControl>().openDoor = true;
        source.sourceTransform = sitPoint.transform;
        source.weight = 1.0f;
        GetComponent<ParentConstraint>().SetSource(0, source);
        yield return new WaitForSeconds(2.5f);
        driving = true;
        Camera.main.GetComponent<ThirdPersonCamera>()._wanted_distance = 15f;
        currCar.GetComponent<CarControl>().openDoor = false;
        Transform Seat = currCar.transform.Find("seat");
        Camera.main.GetComponent<ThirdPersonCamera>().target = Seat;
        source.sourceTransform = Seat.transform;
        source.weight = 1.0f;
        GetComponent<ParentConstraint>().SetSource(0, source);
    }
    /// <summary>
    /// 下车
    /// </summary>
    /// <returns></returns>
    private IEnumerator GetOutCar()
    {
        currCar.GetComponent<CarControl>().engineStopped = true;
        currCar.GetComponent<CarControl>().openDoor = true;
        yield return new WaitForSeconds(2.0f);
        Camera.main.GetComponent<ThirdPersonCamera>()._wanted_distance = 3f;
        GetComponent<ParentConstraint>().constraintActive = false;
        GameObject sitPoint = currCar.transform.Find("sitPoint").gameObject;
        capsuleCollider.enabled = true;
        this.transform.position = sitPoint.transform.position;
        this.transform.rotation = sitPoint.transform.rotation;
        currCar.GetComponent<CarControl>().openDoor = false;
        GetComponent<Rigidbody>().useGravity = true;
        Camera.main.GetComponent<ThirdPersonCamera>().target = this.transform;

    }
    /// <summary>
    /// 消防员重置位置
    /// </summary>
    void ResetplayerPosition()
    {
        this.transform.localPosition = InitialPosition;
        this.transform.localEulerAngles = new Vector3(0, this.transform.eulerAngles.y, 0);
    }
}