//============= 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.UI;
using MyBT;
using UnityEngine.Video;

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

[System.Serializable]
public class NamedMegaPointCache : ComponentHandler {
#if MEGAFIERS_AVAILABLE
    public override string TypeLabel () {
        return "MEGAPOINTCACHE";
    }

    public override string ContentLabel() {
        UpdateComponent();
        return megaPointCache.Label;
    }

    public override void UpdateComponent() {
        base.UpdateComponent();
        megaPointCache = GetComponent<MegaPointCache>();
    }

    public bool active = true;

    public string levelName = "Gletscher";
    public GameObject dummyGletscher;

    public Material overrideMaterial;
    public Renderer renderer;

    public MegaPointCache megaPointCache;

    // public override string titleText {
    //     get {
    //         return "Show/Hide, FadeIn/Out of Renderer using alpha channel of diffuse color";
    //     }
    // }

    // public override string[][] helpText {
    //     get {
    //         return new string[][] {
    //             new string[] {"Run", "Return Success on Press", $"BTC.Run(\"{roomId}\", \"{gameObject.name}\")"},
    //         };
    //     }
    // }

    public void Start() {
        if (active) {
            SceneManager.sceneLoaded += SceneManager_sceneLoaded;
            SceneManager.LoadScene(levelName, LoadSceneMode.Additive);
            Destroy(dummyGletscher);
        } else {
            renderer = dummyGletscher.GetComponent<Renderer>();
        }
    }


    private void SceneManager_sceneLoaded(Scene arg0, LoadSceneMode arg1) {
        // find megapointchache object
        if (megaPointCache == null) {
            MegaPointCache[] megaPointCaches = FindObjectsOfType<MegaPointCache>();
            if (megaPointCaches.Length > 0) {
                megaPointCache = megaPointCaches[0];
            }
            else {
                Debug.LogError("NamedMegaPointCache.UpdateObject: no MegaPointCache found");
            }
            renderer = megaPointCache.GetComponent<Renderer>();
            renderer.sharedMaterial = overrideMaterial;
        }

        // update transform
        GameObject[] rootGameObject = arg0.GetRootGameObjects();
        foreach (GameObject go in rootGameObject) {
            UpdateTransform(go.transform);
        }
    }

    private void UpdateTransform(Transform t) {
        t.position = this.transform.position;
        t.rotation = this.transform.rotation;
        t.localScale = this.transform.localScale;
    }


    public float counter = 0;
    public float playrate = 0.0f;
    public float flowTimeScale = 0.01f;
    public float megaPointCacheTime = 0;
    public string animateShaderVariable = "_Flow_Time";
    private void Update() {
        if (megaPointCache != null) {
            if (megaPointCache.animated) {
                counter += Time.deltaTime * flowTimeScale * playrate;
                SetShaderTime(counter);
            }
            megaPointCacheTime = megaPointCache.time;
        }
    }

    public void OnDisable() {
        SetPlay(false);
    }

    public void SetShaderTime (float time) {
        if (renderer != null) {
            renderer.sharedMaterial.SetFloat(animateShaderVariable, time);
        }
    }

    public void SetFrame (float time) {
        if (megaPointCache != null) {
            megaPointCache.SetAnim(time);
            SetShaderTime(time);
        }
    }
    public float GetFrame () {
        if (megaPointCache != null) {
            return megaPointCache.time;
        } else {
            return 0;
        }
    }
    public void SetPlay (bool playing) {
        if (megaPointCache != null) {
            megaPointCache.animated = playing;
        }
    }
    public void SetPlayRate (float rate) {
        playrate = rate;
        if (megaPointCache != null) {
            megaPointCache.speed = rate;
        }
    }

    // public override void Run(MyBT.NodeState nodeState) {
    //     // whan aborting
    //     if (nodeState == NodeState.Aborting) {
    //         animation.Stop();
    //         return;
    //     }

    //     // at start
    //     if (nodeState == NodeState.FirstRun) {
    //         // reset event trigger
    //         animation.Play();
    //     }
    
    //     // during runtime
    //     if (nodeState == NodeState.Running) {
    //         if (!animation.isPlaying) {
    //             Task.SetSucceeded();
    //             return;
    //         }
    //     }
    // }

    // public override void Set(NodeState nodeState, string key, string value) {
    //     if (nodeState == NodeState.FirstRun) {
    //         if (key == "text") {
    //             Task.SetSucceeded();
    //             return;
    //         }
    //     }
    //     Task.SetFailed();
    // }

    // public override void Update() {
    //     base.Update();
    // }

    #region both values setting
    // public override void SetAlpha(float alpha) {
    //     if (text != null) {
    //         Color col = text.color;
    //         col.a = 1 - alpha;
    //         text.color = col;
    //     }
    // }

    // public override float GetAlpha() {
    //     if (text != null) {
    //         return 1-text.color.a;
    //     }
    //     return 0;
    // }
    #endregion
#else
        [Header("Megafiers Support disabled: Window->MyBT->PreCompiler Definitions")]
        public string dummy;
#endif
}