/**********************************************************************************
* Blueprint Reality Inc. CONFIDENTIAL
* 2020 Blueprint Reality Inc.
* All Rights Reserved.
*
* NOTICE:  All information contained herein is, and remains, the property of
* Blueprint Reality Inc. and its suppliers, if any.  The intellectual and
* technical concepts contained herein are proprietary to Blueprint Reality Inc.
* and its suppliers and may be covered by Patents, pending patents, and are
* protected by trade secret or copyright law.
*
* Dissemination of this information or reproduction of this material is strictly
* forbidden unless prior written permission is obtained from Blueprint Reality Inc.
***********************************************************************************/

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

namespace BlueprintReality.Interprocess.Textures
{
    public class SharedSurfaceWriter
    {
        private int writerIndex;

        private IntPtr updateTextureFunc;

        public SharedSurfaceWriter(string frameId)
        {
            updateTextureFunc = GetWriteToSharedTextureFunc();

            writerIndex = CreateSharedTextureWriter(frameId);

        }

        public void Dispose()
        {
            DisposeSharedTextureWriter(writerIndex);
        }

        public bool WaitUntilReadyForWrite(int timeout = -1)
        {
            return WaitForWriteSignal(writerIndex, timeout);
        }
        public void WriteFrame(Texture srcTex, ulong syncTime, ulong renderTime, ulong frameIndex)
        {
            UpdateSharedTextureWriterState(writerIndex, srcTex.GetNativeTexturePtr(), syncTime, renderTime, frameIndex);

            GL.IssuePluginEvent(updateTextureFunc, writerIndex);
        }

        public void SignalEndOfStream()
        {
            SignalEndOfStream(writerIndex);
        }

        [DllImport(MixCastInteropPlugin.DllName)]
        private static extern int CreateSharedTextureWriter([MarshalAs(UnmanagedType.LPWStr)] string frameId);
        [DllImport(MixCastInteropPlugin.DllName)]
        private static extern int DisposeSharedTextureWriter(int writerIndex);

        [DllImport(MixCastInteropPlugin.DllName)]
        private static extern bool WaitForWriteSignal(int writerIndex, int timeout);
        [DllImport(MixCastInteropPlugin.DllName)]
        private static extern void UpdateSharedTextureWriterState(int writerIndex, IntPtr srcTex, ulong syncTime, ulong renderTime, ulong frameIndex);
        [DllImport(MixCastInteropPlugin.DllName)]
        private static extern void SignalEndOfStream(int writerIndex);

        [DllImport(MixCastInteropPlugin.DllName)]
        private static extern IntPtr GetWriteToSharedTextureFunc();
    }
}
