package jp.sourceforge.nicoro;

import android.annotation.SuppressLint;
import android.os.Handler;
import android.os.Looper;
import android.os.MessageQueue;

import jp.gr.java_conf.shiseissi.commonlib.HandlerThreadCompat;

public abstract class LooperThread extends HandlerThreadCompat implements Handler.Callback {

	public static class WatchIdleWrapper {
        private LooperThread loaderThread;
        private boolean isIdle = true;
        private MessageQueue.IdleHandler idleHandler = new MessageQueue.IdleHandler() {
            @Override
            public boolean queueIdle() {
                isIdle = true;
                return false;
            }
        };
        private Runnable postIdleHandler = new Runnable() {
            @Override
            public void run() {
                Looper.myQueue().addIdleHandler(idleHandler);
            }
        };

        public WatchIdleWrapper(LooperThread lt) {
            loaderThread = lt;
        }
        public boolean isIdle() {
            return isIdle;
        }
        public void postIdleHandler() {
            isIdle = false;
            loaderThread.getHandler().post(postIdleHandler);
        }
        public void startIfNeeded() {
            if (loaderThread.getState() == Thread.State.NEW) {
                loaderThread.start();
            }
        }
        @SuppressLint("NewApi")
        public void quit() {
            loaderThread.quit();
        }
        public Handler getHandler() {
            return loaderThread.getHandler();
        }
    }

    private Handler mHandler;

	protected LooperThread(String name) {
		super(name);
	}

	protected LooperThread(String name, int priority) {
		super(name, priority);
	}

	@Override
	public void start() {
		super.start();
		mHandler = new Handler(getLooper(), this);
	}

	public Handler getHandler() {
		return mHandler;
	}
}
