//============= 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;

#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 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());
                //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();
                }
                //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);
                    Task.SetSucceeded();
                }
                break;
            case NodeState.Aborting:
                // Debug.Log("Testing "+Time.frameCount);
                // depthkitClip.Player.CreatePlayer();
                // depthkitClip.Player.Load();
                //depthkitClip.Player.Stop();
                //if (GetComponent<RenderHeads.Media.AVProVideo.MediaPlayer>()) {
                //    GetComponent<RenderHeads.Media.AVProVideo.MediaPlayer>().Stop();
                //}
                depthkitClip.player.Stop();
                // if (depthkitClip.Player.IsPlayerSetup()) {
                //     Debug.Log("stopping");
                //     depthkitClip.Player.Stop();
                // } 
                // else {
                //     Debug.Log("not stopping");
                // }

                break;
        }
    }

    public override void Show (MyBT.NodeState nodeState) {
        switch (nodeState) {
            case NodeState.FirstRun:
                gameObject.SetActive(true);
                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:
                gameObject.SetActive(false);
                goto case NodeState.Running;
            case NodeState.Running:
                Task.SetSucceeded();
                break;
            
            case NodeState.Aborting:
                break;
            case NodeState.NotRunning:
                break;
        }
    }
#else
        [Header("Depthkit Support disabled: Window->MyBT->PreCompiler Definitions")]
        public string dummy;
#endif
}