using System.Threading;

namespace VCommon.Services
{
    public abstract class ThreadedServiceBase : IService
    {
        private Thread _innerThread;

        public string Tag { get; }
        public bool IsBackground { get; }

        protected ThreadedServiceBase(string tag = null, bool isBackground = true)
        {
            Tag = tag;
            IsBackground = isBackground;
        }

        public void Start()
        {
            if (null != _innerThread) return;

            OnStart();

            _innerThread = new Thread(Run) { IsBackground = IsBackground };
            if (null != Tag) _innerThread.Name = Tag;
            _innerThread.Start();
        }

        protected void Join(int ms) => _innerThread.Join(ms);

        public void Stop()
        {
            if (null == _innerThread) return;
            OnStop();

            _innerThread.Abort();
            _innerThread = null;
        }

        protected virtual void OnStop()
        {
        }

        protected virtual void OnStart()
        {
        }

        protected abstract void Run();
    }
}