package com.bgycc.smartcanteen.task;

import android.os.Bundle;
import org.json.JSONObject;

public class AsyncTask implements Runnable {

    protected long mLastRunTime = 0;
    protected int mStep = 0;
    protected int mProgress = 0;
    protected int mDelay = 0;
    protected long mTimeout = 0;
    protected Runnable mTimeoutRunnable = null;

    protected AsyncTask() {
        init();
    }

    protected void init() {

    }

    @Override
    public void run() {
        long time = System.currentTimeMillis();
        if (mLastRunTime == 0) mLastRunTime = time;
        long expendTime = time - mLastRunTime;
        mLastRunTime = time;

        if (mDelay > 0) {
            mDelay -= expendTime;
            if (mDelay > 0) return;
        }
        if (mTimeout > 0) {
            mTimeout -= expendTime;
            if (mTimeout <= 0 && mTimeoutRunnable != null) {
                mTimeoutRunnable.run();
            }
        }
        run(mStep, mProgress);
    }

    public void callback(JSONObject args) {

    }

    public void callback(Bundle args) {

    }

    protected void resetStep() {
        mProgress = 0;
        mDelay = 0;
        clearTimeout();
    }

    protected void restart() {
        resetStep();
        mStep = 0;
    }

    protected void nextStep() {
        resetStep();
        mStep++;
    }

    protected void nextProgress() {
        mProgress++;
    }

    protected void delay(int delay) {
        mDelay = delay;
    }

    protected void clearTimeout() {
        mTimeout = 0;
        mTimeoutRunnable = null;
    }

    protected void timeout(Runnable runnable, long timeout) {
        mTimeout = timeout;
        mTimeoutRunnable = runnable;
    }

    protected void run(int step, int progress) {

    }
}