package com.sipai.jspatrol.NFC;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.PendingIntent;
import android.content.Intent;
import android.content.IntentFilter;
import android.nfc.NdefMessage;
import android.nfc.NdefRecord;
import android.nfc.NfcAdapter;
import android.nfc.tech.MifareClassic;
import android.nfc.tech.NfcA;
import android.os.Bundle;
import android.os.Parcelable;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.sipai.jspatrol.R;

/**
 * 
 *
 * @see
 * @des
 * 
 *      Nfc 标签的扫描
 * 
 * 
 */
@SuppressLint("NewApi")
public class ReadTag extends Activity {
	private NfcAdapter nfcAdapter;
	private TextView resultText;
	private PendingIntent pendingIntent;
	private IntentFilter[] mFilters;
	private String[][] mTechLists;
	private Button mJumpTagBtn;
	private boolean isFirst = true;
	// 是否支持NFC功能的标签  
    private boolean isNFC_support = false;  
	@SuppressLint("NewApi")
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		// 获取nfc适配器，判断设备是否支持NFC功能
		nfcAdapter = NfcAdapter.getDefaultAdapter(this);
		if (nfcAdapter == null) {
			Toast.makeText(this, getResources().getString(R.string.no_nfc),
					Toast.LENGTH_SHORT).show();
//			finish();
//			return;
		} else if (!nfcAdapter.isEnabled()) {
			Toast.makeText(this, getResources().getString(R.string.open_nfc),
					Toast.LENGTH_SHORT).show();
//			finish();
//			return;
		}
		
		setContentView(R.layout.read_tag);
		TextView tv_title = findViewById(R.id.moudle_back_title_tv_title);
		tv_title.setText("NFC读取");
		ImageView btn_back = findViewById(R.id.moudle_back_title_iv_back);
		btn_back.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				finish();
			}
		});
		TextView tv_right = (TextView) findViewById(R.id.moudle_back_title_tv_save);
		tv_right.setText("写入");
		tv_right.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View view) {
				Intent intent = new Intent(ReadTag.this,WriteTag.class);
				startActivity(intent);
			}
		});
		// 显示结果Text
		resultText = (TextView) findViewById(R.id.resultText);
		// 写入标签按钮
		mJumpTagBtn = (Button) findViewById(R.id.jump);
		mJumpTagBtn.setOnClickListener(new WriteBtnOnClick());

		pendingIntent = PendingIntent.getActivity(this, 0, new Intent(this,
				getClass()).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), 0);
		IntentFilter ndef = new IntentFilter(NfcAdapter.ACTION_TECH_DISCOVERED);
		ndef.addCategory("*/*");
		mFilters = new IntentFilter[] { ndef };// 过滤器
		mTechLists = new String[][] {
				new String[] { MifareClassic.class.getName() },
				new String[] { NfcA.class.getName() } };// 允许扫描的标签类型

	}

	@SuppressLint("NewApi")
	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		nfcAdapter = NfcAdapter.getDefaultAdapter(this);
		if (nfcAdapter==null||!nfcAdapter.isEnabled()) {
			isNFC_support=false;
		}else{
			isNFC_support=true;
		}
		if (isNFC_support) {
			nfcAdapter.enableForegroundDispatch(this, pendingIntent, mFilters,
					mTechLists);
			if (NfcAdapter.ACTION_TECH_DISCOVERED.equals(getIntent().getAction())) {
				// 注意这个if中的代码几乎不会进来，因为刚刚在上一行代码开启了监听NFC连接，下一行代码马上就收到了NFC连接的intent，这种几率很小  
	            // 处理该intent  
				String result = processIntent(getIntent());
				resultText.setText(result);
			}
//			isFirst = false;
		}

	}
	@Override
	protected void onPause() {
		super.onPause();
		if (nfcAdapter !=null && nfcAdapter.isEnabled()) {
			// 当前Activity如果不在手机的最前端，就停止NFC设备连接的监听
			stopNFC_Listener();
		}
	}
	private void stopNFC_Listener() {
		// 停止监听NFC设备是否连接
		nfcAdapter.disableForegroundDispatch(this);
	}
	@Override
	protected void onNewIntent(Intent intent) {
		// TODO Auto-generated method stub
		// 当前app正在前端界面运行，这个时候有intent发送过来，那么系统就会调用onNewIntent回调方法，将intent传送过来  
        // 我们只需要在这里检验这个intent是否是NFC相关的intent，如果是，就调用处理方法  
		super.onNewIntent(intent);
		if (NfcAdapter.ACTION_TECH_DISCOVERED.equals(intent.getAction())) {
			String result = processIntent(intent);
			resultText.setText(result);
		}
	}

	/**
	 * 获取tab标签中的内容
	 * 
	 * @param intent
	 * @return
	 */
	@SuppressLint("NewApi")
	private String processIntent(Intent intent) {
		Parcelable[] rawmsgs = intent
				.getParcelableArrayExtra(NfcAdapter.EXTRA_NDEF_MESSAGES);
		if (rawmsgs!=null) {
			NdefMessage msg = (NdefMessage) rawmsgs[0];
			NdefRecord[] records = msg.getRecords();
			String resultStr = new String(records[0].getPayload());
			return resultStr;
		}else{
			return "error";
		}
		
		
	}

	/**
	 * 按钮点击事件
	 * 
	 *
	 * 
	 */
	class WriteBtnOnClick implements OnClickListener {

		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub
			switch (v.getId()) {
			case R.id.jump:
				Intent intent = new Intent(ReadTag.this, WriteTag.class);
				startActivity(intent);
			default:
				break;
			}
		}

	}

}
