package com.handheld.HFDemo;

import android.app.Activity;
import android.content.Intent;
import android.nfc.NfcAdapter;
import android.nfc.Tag;
import android.os.Bundle;
import android.provider.Settings;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;

import cn.pda.serialport.Tools;

import com.handheld.apiinstructions.R;
import com.handheld.apiinstructions.SettingActivity;
import com.handheld.apiinstructions.Util;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


public class NFCActivity extends Activity implements NfcAdapter.ReaderCallback {

    private NfcAdapter nfcAdapter;

    private TextView editNfcCount;
    private Button buttonClear;
    private ListView lvDataList;
    private Button buttonExit;

    private List<NFC> listNfc = new ArrayList<NFC>();
    private List<Map<String, String>> listMap;

    private SimpleAdapter adapter = null;

    @Override
    public void onTagDiscovered(Tag tag) {
        byte[] uidRaw = tag.getId();
        String uid = Tools.Bytes2HexString(uidRaw, uidRaw.length);
        runOnUiThread(() -> {
            Toast.makeText(NFCActivity.this, "UID: " + uid, Toast.LENGTH_SHORT).show();
        });
        String[] techList = tag.getTechList();
        sortAndadd(listNfc, techList, uid);
        runOnUiThread(() -> {
            addListView();
            editNfcCount.setText(String.valueOf(listNfc.size()));
        });

        Util.play(1, 0);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_nfc);
        nfcAdapter = NfcAdapter.getDefaultAdapter(NFCActivity.this);
        if (nfcAdapter == null) {
            Toast.makeText(NFCActivity.this, "NFC is not available", Toast.LENGTH_SHORT).show();
            finish();
            return;
        } else {
            Toast.makeText(NFCActivity.this, "NFC available", Toast.LENGTH_SHORT).show();
        }

        Bundle options = new Bundle();
        options.putInt(NfcAdapter.EXTRA_READER_PRESENCE_CHECK_DELAY, 250);
        nfcAdapter.enableReaderMode(NFCActivity.this, NFCActivity.this,
                NfcAdapter.FLAG_READER_NFC_A |
                        NfcAdapter.FLAG_READER_NFC_B |
                        NfcAdapter.FLAG_READER_NFC_V,
                options);


        initView();
        Util.initSoundPool(NFCActivity.this);
    }

    private void initView() {
        editNfcCount = (TextView) findViewById(R.id.editText_nfc_count);
        buttonClear = (Button) findViewById(R.id.button_clear);
        lvDataList = (ListView) findViewById(R.id.listView_data_list);
        buttonExit = (Button) findViewById(R.id.button_exit);

        listener();
    }

    private void listener() {
        buttonClear.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                editNfcCount.setText("0");
                listNfc.removeAll(listNfc);
                lvDataList.setAdapter(null);
            }
        });
        buttonExit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (nfcAdapter != null) {
            if (!nfcAdapter.isEnabled()) {
                Toast.makeText(NFCActivity.this, "You need to enable NFC", Toast.LENGTH_SHORT).show();
                Intent intent = new Intent(Settings.ACTION_WIRELESS_SETTINGS);
                startActivity(intent);
            }
            Bundle options = new Bundle();
            options.putInt(NfcAdapter.EXTRA_READER_PRESENCE_CHECK_DELAY, 250);
            nfcAdapter.enableReaderMode(NFCActivity.this, NFCActivity.this,
                    NfcAdapter.FLAG_READER_NFC_A |
                    NfcAdapter.FLAG_READER_NFC_B |
                    NfcAdapter.FLAG_READER_NFC_V,
                    options);
        } else {
            Toast.makeText(NFCActivity.this, "NFC adapter null", Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (nfcAdapter != null)
            nfcAdapter.disableReaderMode(NFCActivity.this);
    }

    public String what = "nfc";
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if(item.getItemId() == R.id.action_settings){
            Intent intent = new Intent(NFCActivity.this, SettingActivity.class);
            intent.putExtra("what", what);
            startActivity(intent);
        }
        return super.onOptionsItemSelected(item);
    }

    private void addListView() {
        listMap = new ArrayList<Map<String, String>>();
        int id = 1;
        for (NFC nfc : listNfc) {
            Map<String, String> map = new HashMap<String, String>();
            map.put("id", id + "");
            map.put("type", nfc.getTech());
            map.put("uid", nfc.getUid());
            map.put("count", nfc.getCount() + "");
            listMap.add(map);
        }
        adapter = new SimpleAdapter(NFCActivity.this, listMap, R.layout.nfc_listview_item,
                new String[] { "id", "type", "uid", "count", }, new int[] {
                R.id.textView_id,
                R.id.textView_type,
                R.id.textView_uid,
                R.id.textView_count });
        lvDataList.setAdapter(adapter);
        adapter.notifyDataSetChanged();
    }

    private List<NFC> sortAndadd(List<NFC> list, String[] tech, String uid) {
        NFC goods = new NFC(tech, uid, 1);

        for (int i = 0; i < list.size(); i++) {
            if (uid.equals(list.get(i).getUid())) {
                goods.setCount(list.get(i).getCount() + 1);
                list.set(i, goods);
                return list;
            }
        }

        list.add(goods);  // Add new NFC if not found
        return list;
    }

    private class NFC {
        private int id;
        private String[] techList;
        private String uid;
        private int count;

        public NFC(String[] tech, String uid, int count) {
            super();
            this.techList = tech;
            this.uid = uid;
            this.count = count;
        }

        public NFC() {
            super();
        }

        public void setId(int id) {
            this.id = id;
        }
        public int getId() {
            return this.id;
        }

        public String[] getTechList() {
            return this.techList;
        }
        public String getTech() {
            String techs = String.join(", ", this.techList);
            return techs.replaceAll("android.nfc.tech.", "");
        }

        public void setUid(String uid) {
            this.uid = uid;
        }
        public String getUid() {
            return this.uid;
        }

        public void setCount(int count) {
            this.count = count;
        }
        public int getCount() {
            return this.count;
        }
        public int incCount() {
            this.count++;
            return this.count;
        }
    }

}
