using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Playables;
using UnityEngine.Timeline;
using DG.Tweening;

public class omObjectJetFighter : omIObject
{
    [Header("GameObject Setting")]
    public GameObject hook_rotation;                                    // Hook Rotation 관련
    public GameObject hookObj;                                          // Hook Object 담는 변수
    public GameObject[] wheel;                                          // 바퀴 오브젝트 담는 변수
    public GameObject wheelTest1;
    public GameObject wheelTest2;
    public GameObject[] fireParticle;                                   // 불 오브젝트 담는 변수
    public ParticleSystem[] dustParticle;                               // 먼지 파티클 넣는 변수
    public Transform MovePoint;

    [Header("Fighter Select Setting")]
    public bool F16Training;
    public bool T50Training;

    [Header("Combat Plane Setting")]
    [Tooltip("속도 조절")]
    public float speed = 15.0f;
    [Tooltip("비행기가 멈추는 위치")]
    public Transform finishPoint;
    [Tooltip("비행기가 뒤로가는 위치")]
    public Transform BackPoint;
    public AudioClip[] combatPlaneSound;                                       // 사운드 재생 목록 및 재생 목록         
    public List<AudioSource> audioSource = new List<AudioSource>();

    [Header("TimeLine")]
    public PlayableDirector playableDirector;                           // Timeline이 실행될 Object를 담는 변수
    public TimelineAsset timeline;                                      // 제작한 Timeline을 넣는 변수

    [Header("Bool Settiing")]
    public bool toFinish = false;                                       // bool 값 사용하기 위한 변수
    public bool toFinishStop = false;
    public bool toBack = false;
    public bool toBackStop = false;
    // private bool hookUpTrigger = false;                                 // Hook OntriggerEnter에 사용할 bool 값
    float wheelX;

    omMap_TailHook m_MapTailhook;
    //omNetObject netObj;

    void Awake()
    {
        m_ObjectType = eObjectType.ActObjT_JetFighter;
        m_MapTailhook = GameObject.Find("Manager").GetComponent<omMap_TailHook>();

        FindWheelSet();
        HookDown();
    }
    void Start()
    {
        foreach (AudioSource AS_3E in GetComponents<AudioSource>())
        {
            audioSource.Add(AS_3E);
        }
        StartCoroutine(ForSoundPlay());

        Invoke("FindWheelSet", 5f);
        InvokeRepeating("WheelRotation", 3f, 0.01f);
    }

    void FixedUpdate()
    {
        if (toFinish == false)
        {
            toFinish = true;
            PlayTimeLine();

            // 누르면 코루틴 실행
            StartCoroutine(ToFinishPointMoveCoroutine());
        }
        toFinishPoint();

        ////지정된 도착 위치로 이동

        //if (toBack == false)
        //{
        //    toBack = true;
        //    StartCoroutine(MoveBackCouroutine());
        //}
        //MoveToBack();
    }
    void FindWheelSet()
    {
        wheelTest1 = GameObject.Find("WheelSet").transform.Find("wheel_01").gameObject;
        wheelTest2 = GameObject.Find("WheelSet").transform.Find("wheel_02").gameObject;
    }

    // 시네머신 시작
    void PlayTimeLine()
    {
        playableDirector.gameObject.SetActive(true);
        playableDirector.Play();
    }
    // finishpoint까지 움직이는 함수 >> 여기 수정
    void toFinishPoint()
    {
        if (toFinishStop == true)
        {
            // 리소스 변경시 duration 변경. 위치까지 얼마나 걸리는 지
            this.transform.position = Vector3.Lerp(transform.position, finishPoint.position, 0.004f);
        }
    }
    // 시작시 훅을 내리기 위함 >> F16과 T50이 내려가는 정도가 다르다 하여 나눔
    void HookDown()
    {
        if (m_MapTailhook.F16Start == true)
        {
            hook_rotation.transform.DOLocalRotateQuaternion(Quaternion.Euler(20, 0, 0), 2.8f);
        }
        else if (m_MapTailhook.T50Start == true)
        {
            // 기획서 나오면 추후 수정
            hook_rotation.transform.DOLocalRotateQuaternion(Quaternion.Euler(20, 0, 0), 2.8f);
        }
    }

    // 바퀴 제자리 굴리는 함수 (Invoke로 사용중)
    void WheelRotation()
    {
        wheelX += Time.deltaTime * 500;
        // Rotation Test
        for (int i = 0; i < 2; i++)
        {
            wheelTest1.transform.rotation = Quaternion.Euler(wheelX, 90, 0);
            wheelTest2.transform.rotation = Quaternion.Euler(wheelX, 90, 0);
        }
    }

    // 이동, Delay Couroutine
    IEnumerator ToFinishPointMoveCoroutine()
    {
        // Debug.Log("코루틴 앞으로");
        yield return new WaitForSeconds(10f);

        //  Debug.Log("코루틴 멈춤");
        yield return new WaitForSeconds(15f);
        // Update에서 멈추기 위함
        toFinishStop = false;
    }

    // Hook이 일직선에서 아래로 움직이다 멈추는 코루틴
    IEnumerator HookDownStop()
    {
        yield return new WaitForSeconds(1.5f);

        while (hook_rotation.transform.localRotation.x > 0.05f)
        {
            hook_rotation.transform.Rotate(-Vector3.right, Time.deltaTime * 0.01f);
            yield return null;
        }
    }

    // Hook이 올라가는 함수
    IEnumerator HookUp()
    {
        Debug.Log("훅 올라감");
        while (hook_rotation.transform.localRotation.x < -0.01f)
        {
            Debug.Log(hook_rotation.transform.localRotation.x);
            hook_rotation.transform.DORotate(-Vector3.right, 2f);
            yield return null;
        }
    }
    // 파티클 제어 코루틴
    IEnumerator Particle_Control()
    {
        // 케이블에 닿을 때, Particle Start
        for (int i = 0; i < dustParticle.Length; i++)
        {
            dustParticle[i].Play();
        }

        yield return new WaitForSeconds(4f);

        // 시간 값 만큼 대기후, Particle Stop
        for (int i = 0; i < dustParticle.Length; i++)
        {
            dustParticle[i].Stop();
        }
    }
    // 오디오 제어 코루틴
    IEnumerator ForSoundPlay()
    {
        yield return new WaitForSeconds(6.0f);

        // 1초간 재생
        audioSource[0].clip = combatPlaneSound[0];
        audioSource[0].Play();
        yield return new WaitForSeconds(1.5f);

        // 2초간 재생
        audioSource[1].clip = combatPlaneSound[1];
        audioSource[1].Play();
        yield return new WaitForSeconds(2.0f);

        // 2초간 재생
        audioSource[2].clip = combatPlaneSound[2];
        audioSource[2].Play();
        yield return new WaitForSeconds(1.5f);

        audioSource[3].clip = combatPlaneSound[3];
        audioSource[3].Play();
        yield return new WaitForSeconds(4f);

        // 도착 및 페이드 사운드
        audioSource[3].Stop();
        audioSource[4].clip = combatPlaneSound[4];
        audioSource[4].Play();
        audioSource[4].loop = true;
    }

    void OnTriggerEnter(Collider col)
    {
        if (col.gameObject.name == "Change_Line" || col.gameObject.name == "Cable1" || col.gameObject.name == "Cable2")
        {
            toFinishStop = true;
            // Change_Line 라는 Object와 부딪히면 먼지 파티클 생성
            StartCoroutine(Particle_Control());
        }
        if (col.gameObject.name == "FinishPoint")
        {
            toBackStop = true;
            // 도착 후 훅 내림
            hook_rotation.transform.DOLocalRotateQuaternion(Quaternion.Euler(5, 0, 0), 3f);
            CancelInvoke("WheelRotation");
        }
        // 이 포인트에 부딪히면 F-16 삭제
        if (col.gameObject.name == "DestroyPoint")
        {
            Destroy(this.gameObject);
            this.gameObject.SetActive(false);
        }
    }
    void OnTriggerExit(Collider collider)
    {
        if (collider.gameObject.name == "FinishPoint")
        {
            Invoke("WheelRotation", 0);
        }
    }
}