package com.yanzuoguang.util.thread;


import com.yanzuoguang.util.extend.ConfigBase;
import com.yanzuoguang.util.log.Log;

import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;

/**
 * 等待某个任务完成后才能继续往下执行
 * @author 颜佐光
 */
public class ThreadWait {

    /**
     * 需要判断的任务
     */
    private ThreadWaitExecute execute;

    /**
     * 取消定时任务
     */
    private Timer timer;

    /**
     * 时间
     */
    private volatile long time;

    /**
     * 构造函数
     *
     * @param execute 需要判断的对象
     * @description 构造函数
     */
    public ThreadWait(ThreadWaitExecute execute) {
        this.execute = execute;
    }

    /**
     * 等待任务完成
     *
     * @return void
     * @description
     */
    public synchronized void waitFinally() {
        if (this.execute == null) {
            return;
        }
        if (!this.execute.isFinally()) {
            this.activePrint();
            try {
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            this.stopPrint();
        }
        if (ConfigBase.PRINT_THREAD) {
            Log.info(ThreadWait.class, "客户端结束时间");
        }
    }

    /**
     * 当完成一任务时,用该函数进行通知,用于进行下一次判断
     *
     * @return void
     * @description
     */
    public void nexted() {
        this.time = System.currentTimeMillis();
    }

    /**
     * 结束运行
     */
    public synchronized void finish() {
        if (this.execute.isFinally()) {
            this.notify();
            if (ConfigBase.PRINT_THREAD) {
                Log.info(ThreadWait.class, "客户端结束时间");
            }
        }
    }

    /**
     * 启动定时任务,用于定时打印状态
     *
     * @param
     * @return void
     * @description
     */
    private synchronized void activePrint() {
        if (this.execute == null) {
            return;
        }
        this.stopPrint();
        if (!this.execute.isFinally()) {
            this.time = System.currentTimeMillis();
            this.timer = new Timer();
            this.timer.schedule(new TimerTask() {
                @Override
                public void run() {
                    Date now = new Date();
                    if (now.getTime() - time > execute.printTimeout()) {
                        execute.printStatus();
                    }
                }
            }, this.execute.printTimeout());
        }
    }

    /**
     * 停止打印状态
     *
     * @param
     * @return void
     * @description
     */
    private synchronized void stopPrint() {
        if (this.timer != null) {
            this.timer.cancel();
        }
        this.timer = null;
    }

}