using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;

namespace ShopBot.Core
{
    internal class InstanceUnique : IDisposable
    {
        private bool _mMutexOwned;
        private readonly Mutex mMutex;

        public InstanceUnique(string name)
        {
            this.mMutex = new Mutex(false, name);
            this._mMutexOwned = false;
        }

        public void Dispose()
        {
            if (this._mMutexOwned)
            {
                this.mMutex.ReleaseMutex();
            }
        }

        public bool IsRunning()
        {
            this._mMutexOwned = this.mMutex.WaitOne(0, true);
            return !this._mMutexOwned;
        }
    }

    public class StartMutex
    {
        static bool IsMutex;
        public static void Start()
        {
            if (IsMutex == false)
            {
                var instanceUnique = new InstanceUnique(Configuration.Mutex);
                if (instanceUnique.IsRunning())
                {
                    Environment.Exit(0);
                }
                IsMutex = true;
            }
        }
    }
}
