package net.heartshield.prevent;

import android.os.Handler;
import android.os.HandlerThread;

/**
 * @author David Madl (git@abanbytes.eu)
 * @date 2017-05-16
 */
public class BackgroundThread {
    private HandlerThread mBackgroundThread;
    private Handler mBackgroundHandler;
    private String mName;
    private boolean mEverStarted = false;

    public BackgroundThread() {
        mName = "Background";
    }
    public BackgroundThread(String name) {
        mName = name;
    }
    public BackgroundThread(Class clazz) {
        mName = clazz.getName() + "Background";
    }

    public synchronized Handler getHandler() {
        return mBackgroundHandler;
    }

    /** lazy-post handler - discards tasks if we're not running anymore */
    public synchronized void post(Runnable r) {
        if(mBackgroundHandler == null) {
            if(!mEverStarted)
                throw new IllegalStateException("must start BackgroundThread before posting");
            else
                return;
        }
        mBackgroundHandler.post(r);
    }

    public synchronized void start() {
        mBackgroundThread = new HandlerThread(mName);
        mBackgroundThread.start();
        mBackgroundHandler = new Handler(mBackgroundThread.getLooper());
        mEverStarted = true;
    }

    public synchronized void stop() {
        if(mBackgroundThread != null) {
            mBackgroundThread.quitSafely();
            try {
                mBackgroundThread.join();
                mBackgroundThread = null;
                mBackgroundHandler = null;
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}
