package com.nexstreaming.nexplayerengine;

import android.annotation.TargetApi;
import android.os.Build;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.Message;
import android.util.Log;
import android.view.Choreographer;

@TargetApi(Build.VERSION_CODES.JELLY_BEAN)
final class NexVSyncSampler implements Choreographer.FrameCallback, Handler.Callback {

	private volatile long vsyncTimeNanos;

	private static final int MSG_CREATE  = 0;
	private static final int MSG_START = 1;
	private static final int MSG_STOP = 2;

	private final Handler handler;
	private final HandlerThread choreographerThread;
	private Choreographer choreographer;
	boolean enabled = false;

	private NexVSyncSampler() {
		choreographerThread = new HandlerThread("ChoreographerOwner:Handler");
		choreographerThread.start();
		handler = new Handler(choreographerThread.getLooper(), this);
		handler.sendEmptyMessage(MSG_CREATE);
	}

	public void start() {
		handler.sendEmptyMessage(MSG_START);
	}

	public void stop() {
		handler.sendEmptyMessage(MSG_STOP);
	}

	@Override
	public void doFrame(long vsyncTimeNs) {
		vsyncTimeNanos = vsyncTimeNs;
		//Log.e("ethan test", "vsyncTimeNs : " + vsyncTimeNanos);
		choreographer.postFrameCallback(this);
	}

	@Override
	public boolean handleMessage(Message message) {
		switch (message.what) {
			case MSG_CREATE: {
				createInternal();
				return true;
			}
			case MSG_START: {
				startInternal();
				return true;
			}
			case MSG_STOP: {
				stopInternal();
				return true;
			}
			default: {
				return false;
			}
		}
	}

	private void createInternal() {
		choreographer = Choreographer.getInstance();
	}

	private void startInternal() {
		if (!enabled) {
			choreographer.postFrameCallback(this);
			enabled = true;
		}
	}

	private void stopInternal() {
		if (enabled) {
			choreographer.removeFrameCallback(this);
			enabled = false;
			vsyncTimeNanos = 0;
		}
	}

}