package com.scenelibrary.classes;

import java.io.UnsupportedEncodingException;
import java.util.Arrays;
import java.util.concurrent.ExecutionException;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.nfc.NdefMessage;
import android.nfc.NdefRecord;
import android.nfc.NfcAdapter;
import android.nfc.Tag;
import android.nfc.tech.Ndef;
import android.os.AsyncTask;
import android.util.Log;
import android.widget.Toast;

public class NfcHelper extends AsyncTask<Tag, Void, String> {
	public static final String MIME_TEXT_PLAIN = "text/plain";
	public static final String TAG = "NfcDemo";
	public String theResult = "blank";
	public static NfcAdapter mNfcAdapter;
	
	
	
	@Override
	protected String doInBackground(Tag... params){
		Tag tag = params[0];
		
		Ndef ndef = Ndef.get(tag);
		if (ndef == null){
			return null;
		}
		
		NdefMessage ndefMessage = ndef.getCachedNdefMessage();
		
		NdefRecord[] records = ndefMessage.getRecords();
		for (NdefRecord ndefRecord:records){
			if (ndefRecord.getTnf() == NdefRecord.TNF_WELL_KNOWN && Arrays.equals(ndefRecord.getType(), NdefRecord.RTD_TEXT)){
				try{
					return readText(ndefRecord);
				} catch (UnsupportedEncodingException e) {
					Log.e(TAG, "Unsupported Encoding", e);
				}
			} 
		}
		return null;
	}
		
	private String readText(NdefRecord record) throws UnsupportedEncodingException{
		byte[] payload = record.getPayload();
		
		String textEncoding = ((payload[0] & 128) == 0) ? "UTF-8" : "UTF-16";
		
		int languageCodeLength = payload[0] & 0063;
		return new String(payload, languageCodeLength +1, payload.length - languageCodeLength - 1, textEncoding);
	}
	
	@Override
	protected void onPostExecute(String result){
		if (result != null){
			//mTextView.setText("Read content: " + result);
			theResult = result;
			/*if (result.equals("WhiteRight"))
			{
				//health = 50;
			}*/
			//else
				//mTextView.setText("Read content: " + result.toString());
			
			//if (mTextView.toString() == "Read content: WhiteRight")
			//{
				//Intent i = new Intent(getApplicationContext(), GameActivity.class);
		        //startActivity(i);
				//health = 20;
			//}
			//mTextView.setText(mTextView.toString());
		}
	}
}
