package com.sunzee.thread.homepage;

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

/**
 * 长时间或者推送要执行的线程池
 */
public class ThreadPoolHomepage {
    private ScheduledThreadPoolExecutor scheduled;

    private ScheduledFuture<?>
            mScheduledFutureM8,
            mScheduledFutureSet, mScheduledFutureRst, mScheduledFutureWrite, mScheduledFutureD120;
    private HomepageTask
            MTaskRunM8, mTaskRunD120,
            mTaskRunMRst, mTaskRunMSet, mTaskRunWrite;

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

    public void startSetM8() {
        MTaskRunM8 = new HomepageTask(HomepageThreadType.runM8);
        mScheduledFutureM8 = scheduled.scheduleAtFixedRate(MTaskRunM8, 0, 1000, TimeUnit.MILLISECONDS);
    }


    public void startRst(String address) {
        mTaskRunMRst = new HomepageTask(HomepageThreadType.runRst, address);
        mScheduledFutureRst = scheduled.scheduleAtFixedRate(mTaskRunMRst, 0, 1000, TimeUnit.MILLISECONDS);
    }


    public void startSet(String address) {
        mTaskRunMSet = new HomepageTask(HomepageThreadType.runSet, address);
        mScheduledFutureSet = scheduled.scheduleAtFixedRate(mTaskRunMSet, 0, 1000, TimeUnit.MILLISECONDS);
    }

    public void startWrite(String paraAddress, String data) {
        mTaskRunWrite = new HomepageTask(HomepageThreadType.runWrite, paraAddress, data);
        mScheduledFutureWrite = scheduled.scheduleAtFixedRate(mTaskRunWrite, 0, 1000, TimeUnit.MILLISECONDS);
    }

    public void startWriteD120(String paraAddress, String data) {
        mTaskRunD120 = new HomepageTask(HomepageThreadType.runD120, paraAddress, data);
        mScheduledFutureD120 = scheduled.scheduleAtFixedRate(mTaskRunD120, 0, 1000, TimeUnit.MILLISECONDS);
    }

    public void stopWriteD120() {
        stopRead(mTaskRunD120, mScheduledFutureD120);
    }

    public void stopWrite() {
        stopRead(mTaskRunWrite, mScheduledFutureWrite);
    }

    public void stopRst() {
        stopRead(mTaskRunMRst, mScheduledFutureRst);
    }

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


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

    public void stopSetM8() {
        stopRead(MTaskRunM8, mScheduledFutureM8);
    }

    public void stopALLRead() {
        stopWrite();
        stopRst();
        stopSet();
        stopSetM8();
        stopWriteD120();
    }

}
