package com.vntel.cccd.processor;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.nfc.NfcAdapter;
import android.nfc.Tag;
import android.nfc.tech.IsoDep;
import android.os.AsyncTask;
import android.util.Log;

import com.htc.sdk.IDCardReader;
import com.htc.sdk.model.CardResult;
import com.htc.sdk.model.IDCardDetail;
import com.htc.sdk.model.ResultCode;

public class NFCProcessor {
    private final static String TAG = "NFCProcessor";
    private NFCProcessorDelegate mDelegate;
    private ReadTask mReadTask;
    public NFCProcessor(Intent intent, String idNumber, NFCProcessorDelegate delegate) {
        this.mDelegate = delegate;
        Tag tag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
        IsoDep isoDep = IsoDep.get(tag);
        mReadTask = new ReadTask(isoDep, idNumber);
    }

    public void execute() {
        mReadTask.execute();
    }

    private class ReadTask extends AsyncTask<Void, String, Exception> {
        private IsoDep isoDep;
        private String mIdNumber;
        private ReadTask(IsoDep isoDep, String idNumber) {
            this.isoDep = isoDep;
            this.mIdNumber = idNumber;
        }

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
        }

        @SuppressLint("NewApi")
        @Override
        protected Exception doInBackground(Void... params) {
            try {
                publishProgress("NFC_READ_STATE_READING");
                IDCardReader rd = new IDCardReader();
                CardResult result = rd.readData(isoDep, mIdNumber, true, true, true);
                if (result != null && (result.getCode() == ResultCode.SUCCESS || result.getCode() == ResultCode.SUCCESS_WITH_WARNING)) {
                    if (mDelegate != null) {
                        mDelegate.onSuccess(result);
                    }
                }
            } catch (Exception e) {
                if (mDelegate != null) {
                    mDelegate.onFailure(e);
                }
                return e;
            }
            return null;
        }
    }
}
