package com.tcl.factory.ir;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.os.Message;

import com.tcl.factory.utils.Debug;

public class IRReceiver extends BroadcastReceiver {
	private final String TAG = "IRReceiver";
	private final static int MSG_IR = 0;
	private final static int MSG_SERIAL = 1;
	@Override
	public void onReceive(Context context, Intent intent) {
		String action = intent.getAction();
		Message msg = new Message();
		int keycode = intent.getIntExtra("keycode", -1);
		Debug.v(TAG, "[onReceive]keycode=" + keycode);
		msg.arg1 = keycode;
		if (action.equals("com.tcl.factory.ir")) {
			msg.what = MSG_IR;
		} else if (action.equals("com.tcl.factory.Serial")) {
			msg.what = MSG_SERIAL;
		}
		handler.sendMessage(msg);
	}
	
	private Handler handler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case MSG_IR:
				covertRomoteKeyAndSend(msg.arg1);
				break;
			case MSG_SERIAL:
				covertRomoteKeyAndSendSerial(msg.arg1);
				break;
			default:
				break;
			}
		}
	};

	private void covertRomoteKeyAndSend(int keyCode) {

		int cmd_data = (keyCode & 0xff00) >> 8;
		if (cmd_data != 0) {
			Debug.v(TAG, "KEYCODE_FACIR");
			IRManager.parser(keyCode);
		}
	}

	private void covertRomoteKeyAndSendSerial(int keyCode) {

		int cmd_data = (keyCode & 0xff00) >> 8;
		if (cmd_data != 0) {
			Debug.v(TAG, "KEYCODE_FACIR");
			keyCode = keyCode & 0x00ff;
			IRManager.parserSerial(cmd_data,keyCode);
		}
	}
}
