package com.bonait.bnframework.common.helper;

import com.bonait.bnframework.common.helper.I.IThread;
import com.bonait.bnframework.common.helper.mode.ThreadModel;
import java.util.concurrent.ConcurrentHashMap;

public class ThreadManager {
    private static volatile ThreadManager _Instance;

    public static ThreadManager Get() {
        if (_Instance == null)
            _Instance = new ThreadManager();
        return _Instance;
    }

    private ThreadManager() {

    }

    public long RestartInterval = 2000;
    ConcurrentHashMap<String, ThreadModel> ts = new ConcurrentHashMap<>();

    private void Sleep(long millis) {
        try {
            Thread.sleep(millis);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
    }

    public void StartLong(String Key, boolean IsRestart, IThread _thread) {
        if (!ts.containsKey(Key)) {
            ts.put(Key, new ThreadModel());
            ts.get(Key).RunThread = _thread;
            ts.get(Key).ThreadObj = new Thread(() -> {
                MessageLog.ShowInfo("启动线程：" + Key);
                while (!ts.get(Key).IsCancel) {
                    if (IsRestart) {
                        try {
                            ts.get(Key).RunThread.Run();
                        } catch (Exception ex) {
                            MessageLog.ShowError("多线程：" + Key + "运行发生异常，已重启,errorMsg：" + ex.toString());
                            Sleep(RestartInterval);
                        }
                    } else {
                        try {
                            ts.get(Key).RunThread.Run();
                        } catch (InterruptedException e) {
                            MessageLog.ShowError("多线程：" + Key + "运行发生异常，已退出,errorMsg：" + e.toString());
                        }
                    }
                }
                try {
                    ts.get(Key).RunThread.RunComplete();
                    MessageLog.ShowInfo("线程：[" + Key + "]--执行完成");
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
                ts.remove(Key);
            });
            ts.get(Key).ThreadObj.setName(Key);
            ts.get(Key).ThreadObj.start();
        } else {
            MessageLog.ShowWarning("任务-[" + Key + "]-已存在");
        }
    }


    public void Stop(String Key) {
        if (ts.containsKey(Key)) {
            ts.get(Key).IsCancel = true;
        }
    }

}
