package com.bonait.bnframework.HBL.Thread;

import com.bonait.bnframework.HBL.Logs.MessageLog;

import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class ThreadManager {
    private static volatile ThreadManager _Instance;
    private ExecutorService executorService;

    public static ThreadManager get() {
        if (_Instance == null){
            synchronized (ThreadManager.class){
                if (_Instance == null){
                    _Instance = new ThreadManager();
                }
            }
        }
        return _Instance;
    }

    private ThreadManager() {

    }

    public void inti(){
//        int processors = Runtime.getRuntime().availableProcessors();
        executorService = Executors.newCachedThreadPool();
    }

    public void execute(Runnable runnable){
        try{
            executorService.execute(runnable);
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    public long RestartInterval = 3000;
    ConcurrentHashMap<String, ThreadModel> tm = 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, IThreadComplete _thread) {
        if (!tm.containsKey(Key)) {
            tm.put(Key, new ThreadModel());
            tm.get(Key).RunThread = _thread;
            tm.get(Key).ThreadObj = new Thread(() -> {
                MessageLog.ShowInfo("启动线程：" + Key);
                while (!tm.get(Key).IsCancel) {
                    if (IsRestart) {
                        try {
                            tm.get(Key).RunThread.Run();
                        } catch (Exception ex) {
                            MessageLog.ShowError("多线程：[" + Key + "] 运行发生异常，已重启,错误信息：" + ex.toString());
                            Sleep(RestartInterval);
                        }
                    } else {
                        try {
                            tm.get(Key).RunThread.Run();
                        } catch (Exception e) {
                            MessageLog.ShowError("多线程：[" + Key + "] 运行发生异常，已重启,错误信息：" + e.toString());
                        }
                    }
                }
                try {
                    tm.get(Key).RunThread.RunComplete();
                    MessageLog.ShowInfo("线程：[" + Key + "]--执行完成");
                } catch (Exception e) {
                    MessageLog.ShowError("多线程：[" + Key + "] 执行完成任务发生异常，已退出,错误信息：" + e.toString());
                }
                tm.remove(Key);
            });
            tm.get(Key).ThreadObj.setName(Key);
            tm.get(Key).ThreadObj.start();
        } else {
            MessageLog.ShowWarning("任务-[" + Key + "]-已存在");
        }
    }

    public void StartLong(String Key, boolean IsRestart, IThread _thread) {
        if (!tm.containsKey(Key)) {
            tm.put(Key, new ThreadModel());
            tm.get(Key).Task = _thread;
            tm.get(Key).ThreadObj = new Thread(() -> {
                MessageLog.ShowInfo("启动线程：" + Key);
                while (!tm.get(Key).IsCancel) {
                    if (IsRestart) {
                        try {
                            tm.get(Key).Task.Run();
                        } catch (Exception ex) {
                            MessageLog.ShowError("多线程：[" + Key + "] 运行发生异常，已重启,错误信息：" + ex.toString());
                            Sleep(RestartInterval);
                        }
                    } else {
                        try {
                            tm.get(Key).Task.Run();
                        } catch (Exception e) {
                            MessageLog.ShowError("多线程：[" + Key + "] 运行发生异常，已重启,错误信息：" + e.toString());
                        }
                    }
                }
                tm.remove(Key);
            });
            tm.get(Key).ThreadObj.setName(Key);
            tm.get(Key).ThreadObj.start();
        } else {
            MessageLog.ShowWarning("任务-[" + Key + "]-已存在");
        }
    }

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

}
