package com.sipai.jspatrol.NFC;

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

import com.sipai.jspatrol.Fault.SingleChoiceActivity;
import com.sipai.jspatrol.R;

import java.io.IOException;

import cn.pedant.SweetAlert.SweetAlertDialog;

/**
 * 写入标签
 * 
 * @warn：弹出dialog 允许写入
 
 * 
 */
@SuppressLint("NewApi")
public class WriteTag extends Activity {

	private IntentFilter[] mWriteTagFilters;
	private NfcAdapter nfcAdapter;
	PendingIntent pendingIntent;
	String[][] mTechLists;
	Button writeBtn;
	boolean isWrite = false;
	EditText mContentEditText;
	public static final int REQUSET = 1;
	private Button btn_patrolpoint,btn_equ,btn_box;
	private String cname = "";
	public static void actionStart(Context context,String id){
		Intent intent = new Intent(context,WriteTag.class);
		intent.putExtra("id",id);
		context.startActivity(intent);
	}
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.write_tag);
		TextView tv_title = (TextView) findViewById(R.id.moudle_back_title_tv_title);
		tv_title.setText("数据写入");
		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(WriteTag.this,ReadTag.class);
				startActivity(intent);
			}
		});
		ImageView btn_back = (ImageView) findViewById(R.id.moudle_back_title_iv_back);
		btn_back.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				finish();
			}
		});
		writeBtn = (Button) findViewById(R.id.writeBtn);
		writeBtn.setOnClickListener(new WriteOnClick());
		mContentEditText = (EditText) findViewById(R.id.content_edit);
		// 获取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;
		}
		pendingIntent = PendingIntent.getActivity(this, 0, new Intent(this,
				getClass()).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), 0);
		// 写入标签权限
		IntentFilter writeFilter = new IntentFilter(
				NfcAdapter.ACTION_TECH_DISCOVERED);
		mWriteTagFilters = new IntentFilter[] { writeFilter };
		mTechLists = new String[][] {
				new String[] { MifareClassic.class.getName() },
				new String[] { NfcA.class.getName() } };// 允许扫描的标签类型
		Intent intent = getIntent();
		String id = intent.getStringExtra("id");
		if (id!=null&&!id.isEmpty()){
			mContentEditText.setText("");
			mContentEditText.setText(id);
		}
		btn_patrolpoint = (Button) findViewById(R.id.moudle_write_btn_patrolpoint);
		btn_patrolpoint.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View view) {
				Intent intent=new Intent();
				intent.setClass(WriteTag.this, PatrolPointActivity.class);
				startActivityForResult(intent,REQUSET);
			}
		});
		btn_equ = (Button) findViewById(R.id.moudle_write_btn_equ);
		btn_equ.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View view) {
				Intent intent_sel_equ = new Intent(WriteTag.this, SingleChoiceActivity.class);
				intent_sel_equ.putExtra("mark","equ");
				startActivityForResult(intent_sel_equ, REQUSET);
//				Intent intent=new Intent();
//				intent.setClass(WriteTag.this, NFCEquListActivity.class);
//				startActivityForResult(intent,REQUSET);
			}
		});

	}

	@Override
	protected void onRestart() {
		super.onRestart();
//		if (getIntent().getStringExtra("id")!=null){
///
//		}
	}

	/**
	 * 写入标签按钮点击事件监听
	 * 
	 *
	 * 
	 */
	class WriteOnClick implements OnClickListener {

		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub
			runOnUiThread(new Runnable() {
				@Override
				public void run() {


			isWrite = true;
			new SweetAlertDialog(WriteTag.this, SweetAlertDialog.NORMAL_TYPE)
					.setTitleText("提示")
					.setContentText("请将标签靠近！并请在数据写入成功后再点击按钮。")
					.setConfirmText("继续")
					.setConfirmClickListener(new SweetAlertDialog.OnSweetClickListener() {
						@Override
						public void onClick(SweetAlertDialog sweetAlertDialog) {
							sweetAlertDialog.dismissWithAnimation();
							mContentEditText.setText("");
							isWrite = false;
							if (cname!=null&&cname.length()>0) {
								if(cname.equals("equ")){
									Intent intent_sel_equ = new Intent(WriteTag.this, SingleChoiceActivity.class);
									intent_sel_equ.putExtra("mark","equ");
									startActivityForResult(intent_sel_equ, REQUSET);
								}else if (cname.equals("point")){
									Intent intent=new Intent();
									intent.setClass(WriteTag.this, PatrolPointActivity.class);
									startActivityForResult(intent,REQUSET);
								}
							}
						}
					}).setCancelText("取消")
					.setCancelClickListener(new SweetAlertDialog.OnSweetClickListener() {
						@Override
						public void onClick(SweetAlertDialog sweetAlertDialog) {
							sweetAlertDialog.dismissWithAnimation();
							isWrite = false;
						}
					}).show();
				}
			});
		}
	}

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		nfcAdapter.enableForegroundDispatch(this, pendingIntent,
				mWriteTagFilters, mTechLists);
	}
	@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
		super.onNewIntent(intent);
		if (isWrite == true
				&& NfcAdapter.ACTION_TECH_DISCOVERED.equals(intent.getAction())) {
			Tag tag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
			NdefMessage ndefMessage = getNoteAsNdef();
			if (ndefMessage != null) {
				writeTag(getNoteAsNdef(), tag);
			} else {
				showToast("请输入您要写入标签的内容");
			}
		}
	}

	// 根据文本生成一个NdefRecord
	private NdefMessage getNoteAsNdef() {
		String text = mContentEditText.getText().toString();
		if (text.equals("")) {
			return null;
		} else {
			byte[] textBytes = text.getBytes();
			// image/jpeg text/plain
			NdefRecord textRecord = new NdefRecord(NdefRecord.TNF_MIME_MEDIA,
					"image/jpeg".getBytes(), new byte[] {}, textBytes);
			return new NdefMessage(new NdefRecord[] { textRecord });
		}

	}

	// 写入tag
	boolean writeTag(NdefMessage message, Tag tag) {

		int size = message.toByteArray().length;

		try {
			Ndef ndef = Ndef.get(tag);
			if (ndef != null) {
				ndef.connect();

				if (!ndef.isWritable()) {
					showToast("tag不允许写入");
					return false;
				}
				if (ndef.getMaxSize() < size) {
					showToast("文件大小超出容量");
					return false;
				}

				ndef.writeNdefMessage(message);
				runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        new SweetAlertDialog(WriteTag.this, SweetAlertDialog.SUCCESS_TYPE)
                                .setTitleText("成功")
                                .setContentText("数据写入成功")
                                .setConfirmText("确定")
                                .setConfirmClickListener(new SweetAlertDialog.OnSweetClickListener() {
                                    @Override
                                    public void onClick(SweetAlertDialog sweetAlertDialog) {
                                        sweetAlertDialog.dismissWithAnimation();
                                    }
                                }).setCancelText("查看写入数据")
                                .setCancelClickListener(new SweetAlertDialog.OnSweetClickListener() {
                                    @Override
                                    public void onClick(SweetAlertDialog sweetAlertDialog) {
                                        sweetAlertDialog.dismissWithAnimation();
                                        Intent intent = new Intent(WriteTag.this,ReadTag.class);
                                        startActivity(intent);
                                    }
                                }).show();

                    }
                });
				return true;
			} else {
				NdefFormatable format = NdefFormatable.get(tag);
				if (format != null) {
					try {
						format.connect();
						format.format(message);
						showToast("格式化tag并且写入message");
						return true;
					} catch (IOException e) {
						showToast("格式化tag失败.");
						return false;
					}
				} else {
					showToast("Tag不支持NDEF");
					return false;
				}
			}
		} catch (Exception e) {
            new SweetAlertDialog(WriteTag.this, SweetAlertDialog.ERROR_TYPE)
                    .setTitleText("失败")
                    .setContentText("数据写入失败")
                    .setConfirmText("重写")
                    .setConfirmClickListener(new SweetAlertDialog.OnSweetClickListener() {
                        @Override
                        public void onClick(SweetAlertDialog sweetAlertDialog) {
                            sweetAlertDialog.dismissWithAnimation();
                        }
                    }).show();
		}

		return false;
	}

	private void showToast(String text) {
		Toast.makeText(this, text, Toast.LENGTH_SHORT).show();
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {

		}
		return super.onOptionsItemSelected(item);
	}
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, data);
		//requestCode标示请求的标示   resultCode表示有数据
		if (requestCode == WriteTag.REQUSET && resultCode == RESULT_OK) {
			String ppid=data.getStringExtra("ppid");
			cname = data.getStringExtra("class");
			mContentEditText.setText("");
			mContentEditText.setText(ppid);
		}
	}
}
