package com.ntels.onecable.admin.common.websocket;

import com.ntels.onecable.admin.common.util.LogUtil;

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

/**
 * <pre>
 * 1. ClassName :   AsyncTaskCancelTimerTask
 * 2. FileName  :   AsyncTaskCancelTimerTask.java
 * 3. Package   :   com.ntels.onecable.admin.common.websocket
 * 4. Date      :   2016-12-06
 * 5. Author    :   aaron
 * 6. Comment   :   일정 시간 후 AsyncTask 요청을 취소한다.
 * </pre>
 */
public class AsyncTaskCancelTimerTask extends CountDownTimer {

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

    private AsyncTask asyncTask;
    private boolean interrupt;

    /**
     * 생성자.
     *
     * @param asyncTask Target task
     * @param startTime {@link CountDownTimer#CountDownTimer(long, long)}
     * @param interval  {@link CountDownTimer#CountDownTimer(long, long)}
     */
    public AsyncTaskCancelTimerTask(AsyncTask asyncTask, long startTime, long interval) {
        super(startTime, interval);
        this.asyncTask = asyncTask;
    }

    /**
     * 생성자.
     *
     * @param asyncTask Target task
     * @param startTime {@link CountDownTimer#CountDownTimer(long, long)}
     * @param interval  {@link CountDownTimer#CountDownTimer(long, long)}
     * @param interrupt Cancel 여부
     */
    public AsyncTaskCancelTimerTask(AsyncTask asyncTask, long startTime, long interval, boolean interrupt) {
        super(startTime, interval);
        this.asyncTask = asyncTask;
        this.interrupt = interrupt;
    }

    @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();
        }
    }

    @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();
        }
    }
}
