﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using UnityEngine;

namespace BlueprintReality.MixCast
{
    public class SharedTexturePluginUpdater : MonoBehaviour
    {
        private static bool created = false;
        public static void EnsureExists()
        {
            if (!created)
            {
                new GameObject().AddComponent<SharedTexturePluginUpdater>();
                created = true;
            }
        }

        private void Awake()
        {
            name = GetType().Name;
            hideFlags = HideFlags.HideAndDontSave;
            DontDestroyOnLoad(gameObject);
            StartCoroutine("CallPluginAtEndOfFrames");
        }

        private IEnumerator CallPluginAtEndOfFrames()
        {
            while (true)
            {
                // Wait until all frame rendering is done
                yield return new WaitForEndOfFrame();

                GL.IssuePluginEvent(GetRenderEventFunc(), 1);
            }
        }

        [DllImport("ExTexture")]
        private static extern IntPtr GetRenderEventFunc();
    }
}