package com.sunzee.thread;

import android.util.Log;

import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * 通用参数线程池
 */
public class ThreadPoolGeneralParameter {
    private ScheduledThreadPoolExecutor scheduled;

    private ScheduledFuture<?> mScheduledFutureM17;
    private GeneralParameterTask mTaskRunM17;
    private GeneralParameterTask mTaskRstM17;
    private GeneralParameterTask mTaskSetM17;

    public ThreadPoolGeneralParameter() {
        scheduled = new ScheduledThreadPoolExecutor(2);
        //设置线程池的策略  抛弃旧的任务
        scheduled.setRejectedExecutionHandler(new ThreadPoolExecutor.DiscardOldestPolicy());
    }

    private static final String TAG = "ThreadPoolGeneralParame";

    public void startALLRead() {
        mTaskRunM17 = new GeneralParameterTask(GeneralParameterThreadType.runM17);

        mScheduledFutureM17 = scheduled.scheduleAtFixedRate(mTaskRunM17, 10, 1000, TimeUnit.MILLISECONDS);
        Log.d(TAG, "startALLRead: " + mTaskRunM17 + ":" + mScheduledFutureM17);
    }

    public void stopReadM17() {
        stopRead(mTaskRunM17, mScheduledFutureM17);
    }

    public void stopRstM17() {
        stopRead(mTaskRstM17, mScheduledFutureM17);
    }

    public void stopSetM17() {
        stopRead(mTaskSetM17, mScheduledFutureM17);
    }


    public void startRstM17(String address) {
        mTaskRstM17 = new GeneralParameterTask(GeneralParameterThreadType.rstM17);

        mScheduledFutureM17 = scheduled.scheduleAtFixedRate(mTaskRstM17, 10, 100, TimeUnit.MILLISECONDS);
    }


    public void startSetM17(String address) {
        mTaskSetM17 = new GeneralParameterTask(GeneralParameterThreadType.setM17);
        mScheduledFutureM17 = scheduled.scheduleAtFixedRate(mTaskSetM17, 10, 100, TimeUnit.MILLISECONDS);
    }


    public static void stopRead(GeneralParameterTask threadTask, ScheduledFuture<?> scheduledFuture1) {
        if (threadTask != null) {
            threadTask.setIsRun(false);
        }
        if (scheduledFuture1 != null) {
            scheduledFuture1.cancel(true);
        }
    }
}
