package com.ntels.kneet.v3.common.websocket;

import android.os.AsyncTask;
import android.os.CountDownTimer;

import com.ntels.kneet.v3.common.util.LogUtil;

/**
 * 1. ClassName :   AsyncTaskCancelTimerTask
 * 2. FileName  :   AsyncTaskCancelTimerTask.java
 * 3. Package   :   com.ntels.kneet.v3.common.websocket
 * 4. Date      :   2016-06-10
 * 5. Author    :   aaron
 * 6. Comment   :   Initialize
 */
public class AsyncTaskCancelTimerTask extends CountDownTimer {

    private static final String TAG = AsyncTaskCancelTimerTask.class.getSimpleName();

    private AsyncTask asyncTask;
    private boolean interrupt;

    public AsyncTaskCancelTimerTask(AsyncTask asyncTask, long startTime, long interval) {
        super(startTime, interval);
        this.asyncTask = asyncTask;
    }

    public AsyncTaskCancelTimerTask(AsyncTask asyncTask, long startTime, long interval, boolean interrupt) {
        super(startTime, interval);
        this.asyncTask = asyncTask;
        this.interrupt = interrupt;
    }

    /**
     * Callback fired on regular interval.
     *
     * @param millisUntilFinished The amount of time until finished.
     */
    @Override
    public void onTick(long millisUntilFinished) {
        if ( asyncTask == null ) {
            this.cancel();
            return;
        }

        LogUtil.i(TAG, asyncTask.toString() + " onTick..");

        if ( asyncTask.isCancelled() ) {
            this.cancel();
        }

        if ( asyncTask.getStatus() == AsyncTask.Status.FINISHED ) {
            this.cancel();
        }
    }

    /**
     * Callback fired when the time is up.
     */
    @Override
    public void onFinish() {
        LogUtil.i(TAG, "onFinish..");

        if ( asyncTask == null || asyncTask.isCancelled() ) {
            return;
        }

        try {
            if ( asyncTask.getStatus() == AsyncTask.Status.FINISHED ) {
                return;
            }

            if ( asyncTask.getStatus() == AsyncTask.Status.PENDING || asyncTask.getStatus() == AsyncTask.Status.RUNNING ) {
                asyncTask.cancel(interrupt);
            }
        } catch ( Exception e ) {
            e.printStackTrace();
        }
    }
}
