package com.sunzee.thread.generalparameter;

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, mScheduledFutureRst, mScheduledFutureSet;
    private GeneralParameterTask mTaskRunM17;
    private GeneralParameterTask mTaskRunMRst;
    private GeneralParameterTask mTaskRunMSet;

    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 stopRst() {
        stopRead(mTaskRunMRst, mScheduledFutureRst);
    }

    public void stopSet() {
        stopRead(mTaskRunMSet, mScheduledFutureSet);
    }


    public void startRst(String address) {
        mTaskRunMRst = new GeneralParameterTask(GeneralParameterThreadType.runRst, address);
        mScheduledFutureRst = scheduled.scheduleAtFixedRate(mTaskRunMRst, 10, 1000, TimeUnit.MILLISECONDS);
    }


    public void startSet(String address) {
        mTaskRunMSet = new GeneralParameterTask(GeneralParameterThreadType.runSet, address);
        mScheduledFutureSet = scheduled.scheduleAtFixedRate(mTaskRunMSet, 10, 1000, TimeUnit.MILLISECONDS);
    }


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