//============= Copyright (c) Ludic GmbH, All rights reserved. ==============
//
// Purpose: Part of the My Behaviour Tree Controller Code
//
//=============================================================================

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Video;
using MyBT;
using RenderHeads.Media.AVProVideo;

#if DEPTHKIT_AVAILABLE
using static Depthkit.Clip;
#endif

#if UNITY_EDITOR
using UnityEditor;
[CustomEditor(typeof(NamedDepthkitPlayer))]
public class NamedDepthkitPlayerInspector : ComponentHandlerInspector {
}
#endif

[System.Serializable]
public class NamedDepthkitPlayer : ComponentHandler {
#if DEPTHKIT_AVAILABLE
    public override string TypeLabel () {
        return "Depthkit";
    }

    public override string ContentLabel() {
        UpdateComponent();
        // string filename = "dummy-metadatafilepath"; // depthkitClip.metadataFilePath;
        // Debug.Log($"NamedDepthkitPlayer.ContentLabel metadataFilePath {depthkitClip.metadataFilePath}");
        // string filename = depthkitClip.metadataFilePath;
        // Debug.Log($"NamedDepthkitPlayer.ContentLabel metadataFile {depthkitClip.metadataFile}");
        // Debug.Log($"NamedDepthkitPlayer.ContentLabel metadataFile {depthkitClip.metadataFile.name}");
        if (depthkitClip.metadataFile != null) {
            return depthkitClip.metadataFile.name;
        }
        if (depthkitClip.poster != null) {
            return depthkitClip.poster.name;
        }
        if (depthkitClip.player != null) {
            return depthkitClip.player.GetVideoPath();
        }
        return "undefined-contentlabel";
        // if (depthkitClip.metadataFile == null) {
        //     filename = depthkitClip.metadataFile.name;
        // }
        // if (depthkitClip.metadataSourceType == MetadataSourceType.TextAsset) {
        //     filename = depthkitClip.metadataFile.name;
        // }
        // return filename;
    }

    public override void UpdateComponent() {
        base.UpdateComponent();
        depthkitClip = GetComponent<Depthkit.Clip>();
        if (depthkitClip == null) {
            Debug.Log($"NamedDepthkitPlayer.UpdateComponent depthkitClip is null");
        }
    }

    public Depthkit.Clip depthkitClip;
    public string videoPath;
    MediaPlayer mediaPlayer;

    public override string titleText {
        get {
            return "Show/Hide, Run Depthkit Video";
        }
    }

    public override string[][] helpText {
        get {
            return new string[][] {
                new string[] {"Show", null, $"BTC.Show(\"{roomId}\", \"{gameObject.name}\")"},
                new string[] {"Hide", null, $"BTC.Hide(\"{roomId}\", \"{gameObject.name}\")"},
                new string[] {"Run", null, $"BTC.Run(\"{roomId}\", \"{gameObject.name}\")"}
            };
        }
    }

    public override void Run (MyBT.NodeState nodeState) {
        // Debug.Log($"NamedDepthkitPlayer.Run {nodeState}");
        switch (nodeState) {
            case NodeState.FirstRun:
                // depthkitClip.Player.CreatePlayer();
                // depthkitClip.Player.Load();
                //GetComponent<RenderHeads.Media.AVProVideo.MediaPlayer>().Rewind(true);
                //depthkitClip.Player.StartVideoLoad();

                //StartCoroutine(depthkitClip.player.LoadAndPlay());
                
                depthkitClip.player.Play();

                //GetComponent<RenderHeads.Media.AVProVideo.MediaPlayer>().Rewind(false);
                //Debug.Log("NamedDepthkitPlayer.FirstRun: Load "+Time.frameCount);
                // goto case NodeState.Running;
                break;
            case NodeState.Running:
                //if ((depthkitClip.Player.GetCurrentTime() <= 0)) {
                //    //depthkitClip.Player.Play();
                //    GetComponent<RenderHeads.Media.AVProVideo.MediaPlayer>().Play();
                //    Debug.Log("NamedDepthkitPlayer.Running: Play "+depthkitClip.Player.GetCurrentTime());
                //}
                //if (!depthkitClip.Player.IsPlaying()) { //  || GetComponent<RenderHeads.Media.AVProVideo.MediaPlayer>().
                //    //depthkitClip.Player.Play();
                //    GetComponent<RenderHeads.Media.AVProVideo.MediaPlayer>().Play();
                //    //GetComponent<RenderHeads.Media.AVProVideo.MediaPlayer>().Rewind(false);
                //}
                bool isLoaded = (depthkitClip.player.GetDuration() != 0);
                bool isFinishedPlaying = (depthkitClip.player.GetCurrentTime() >= depthkitClip.player.GetDuration() - 0.3f);
                if (isLoaded && !depthkitClip.player.IsPlaying()) {
                    depthkitClip.player.Play();
                }

                if (mediaPlayer.Loop && depthkitClip.player.IsPlaying())
                {
                    Task.SetSucceeded();
                    return;
                }

                //Debug.Log($"[BTC] NamedDepthkitPlayer.Running: Running: {depthkitClip.Player.IsPlaying()} {isLoaded} {isFinishedPlaying} {Time.frameCount} {depthkitClip.Player.GetCurrentTime()} {depthkitClip.Player.GetDuration()}");
                // on desktop 
                if (isFinishedPlaying && isLoaded) {
                    //Debug.Log("[BTC] NamedDepthkitPlayer.Running: !IsPlaying " + Time.frameCount);
                    //depthkitClip.Player.Stop();
                    //GetComponent<RenderHeads.Media.AVProVideo.MediaPlayer>().Rewind(true);
                    mediaPlayer.CloseMedia();
                    Task.SetSucceeded();
                    return;
                }
                break;
        }
    }

    public override void Show (MyBT.NodeState nodeState) {
        switch (nodeState) {
            case NodeState.FirstRun:
                gameObject.SetActive(true);
                mediaPlayer = GetComponent<MediaPlayer>();
                if (mediaPlayer != null)
                {
                    mediaPlayer.OpenMedia(new MediaPath(videoPath, MediaPathType.RelativeToPersistentDataFolder), autoPlay: false);
                }
                goto case NodeState.Running;
            case NodeState.Running:
                Task.SetSucceeded();
                break;
            case NodeState.Aborting:
                break;
        }
    }

    public override void Hide (MyBT.NodeState nodeState) {
        //Debug.Log($"NamedDepthkitPlayer.Hide {nodeState}");
        switch (nodeState) {
            case NodeState.FirstRun:
                if (mediaPlayer != null)
                {
                    if (depthkitClip.player.IsPlaying())
                    {
                        depthkitClip.player.Stop();
                        mediaPlayer.CloseMedia();
                    }
                }
                gameObject.SetActive(false);
                Task.SetSucceeded();
                break;
         /*   case NodeState.Running:
                if (mediaPlayer != null)
                {
                    if (!mediaPlayer.MediaOpened && !depthkitClip.player.IsPlaying())
                    {
                        Debug.Log("MEDIA IS CLOSED!!!");
                        gameObject.SetActive(false);
                        Task.SetSucceeded();
                    }
                    else
                    {
                        depthkitClip.player.Stop();
                        mediaPlayer.CloseMedia();
                    }
                }
                break;
            */
            case NodeState.Aborting:
                if (mediaPlayer != null)
                {
                    mediaPlayer.CloseMedia();
                }
                break;
            case NodeState.NotRunning:
                break;
         
        }
    }
#else
        [Header("Depthkit Support disabled: Window->MyBT->PreCompiler Definitions")]
        public string dummy;
#endif
}