using BlueprintReality.MixCast;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using System.Threading;
using UnityEngine;

namespace BlueprintReality.MixCast.Client
{
    public class ServiceMutexCheck : IDisposable
    {
        Thread waitThread;

        Action lostService;

        public ServiceMutexCheck(Action lostService)
        {
            this.lostService = lostService;

            waitThread = new Thread(WaitForServiceCloseInThread);
            waitThread.Start();
        }

        public void Dispose()
        {
            EndWaitForService();
            waitThread.Join();
        }

        void WaitForServiceCloseInThread()
        {
            if (WaitForServiceClose())
            {
                if (lostService != null)
                    lostService.Invoke();
            }
        }

        [DllImport(Interprocess.MixCastInteropPlugin.DllName)]
        private static extern bool WaitForServiceClose();

        [DllImport(Interprocess.MixCastInteropPlugin.DllName)]
        private static extern void EndWaitForService();
    }
}
