package com.imin;

import android.os.Bundle;
import android.os.Handler;
import android.view.ViewGroup;
import android.widget.Toast;
import android.app.Activity;

import android.content.Context;
import android.util.Log;
import android.os.Looper;

import android.os.Message;
import android.os.Bundle;

import com.imin.nfc.NFCErrorState;
import com.imin.nfc.NFCEventListener;
import com.imin.nfc.NFCManager;

public class Read extends Activity implements NFCEventListener {

    private  Context context = null;
    private static final String TAG = "iminNfc";
    private Handler progressHandler = new Handler();
    private NFCManager nfcManager;
    private boolean openHead;
    private int errrCount = 0;

    public static final int READ_RESPONSE  = 1;
    @Override
    public void onCreate(Bundle state) {
        super.onCreate(state);
        context = this;
        nfcManager = NFCManager.getInstance();
        initNFC();
        // nfcManager.initTouchCard();
        nfcManager.unTouchIcOpenHead();
        runOnUiThread(new Runnable() {
      @Override
      public void run() {
          setContentView(getApplication().getResources().getIdentifier("nfcloader", "layout", getApplication().getPackageName()));
        }
  });


    }
    @Override
    protected void onResume() {
        super.onResume();
        // initNFC();
        // nfcManager.initTouchCard();
        // nfcManager.unTouchIcOpenHead();
    }

    @Override
    protected void onPause() {
        super.onPause();
        nfcManager.CloseNfc();
    }
    @Override
    protected void onDestroy() {
        super.onDestroy();
        nfcManager.destroy();
    }


    @Override
    public void onTouchIcOpenHead() {
         Log.d(TAG,"onTouchIcOpenHead");
        openHead = true;
        nfcManager.touchIcPowerOnReset();
    }

    @Override
    public void onTouchIcCloseHead() {
       Log.d(TAG,"onTouchIcCloseHead");
    }

    @Override
    public void onTouchIcPowerOnReset() {

        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                     Log.d(TAG,"onTouchIcPowerOnReset");
                // clickable(true);
                // powerTextV.setText("NFC open success");
                // powerTextV.setTextColor(getResources().getColor(android.R.color.holo_green_dark));
            }
        });
    }

    @Override
    public void onTouchIcPowerDown() {
 Log.d(TAG,"onTouchIcPowerDown");
    }

    @Override
    public void onTouchIcGetState(int state) {
Log.d(TAG,"onTouchIcGetState");
    }

    @Override
    public void onUnTouchIcOpenHead() {
      Log.d(TAG,"onUnTouchIcOpenHead");
       nfcManager.unTouchIcSearchCard(true);
    }

    @Override
    public void onUnTouchIcCloseHead() {
      Log.d(TAG,"onUnTouchIcCloseHead");
    }

    @Override
    public void onUnTouchIcSearchCard(String cardId) {
            Log.d(TAG,"onUnTouchIcSearchCard");
       handleSearchCard(cardId);
    }

    @Override
    public void onEcashIssueCard() {
            Log.d(TAG,"onEcashIssueCard");
        // handleIssueCard();
    }

    @Override
    public void onEcashLoginOut() {
        Log.d(TAG,"onEcashLoginOut");
        // handleLoginOut();
    }

    @Override
    public void onEcashBalance(int balance) {
              Log.d(TAG,"onEcashBalance");
        // handleBalance(balance);
    }

    @Override
    public void onEcashConsume(int balance) {
                  Log.d(TAG,"onEcashConsume");
        // handleConsume(balance);
    }

    @Override
    public void onEcashDeposit(int balance) {
        Log.d(TAG,"onEcashDeposit");

    }

    @Override
    public void onOccurError( final int errorCode) {
          Log.d(TAG,"onOccurError");

        new android.os.Handler(Looper.getMainLooper()).postDelayed(
            new Runnable() {
                public void run() {
                    Log.i("tag", "This'll run 300 milliseconds later");
                  Log.d(TAG,"error count = "+errrCount);
                      if (  errrCount == 15) {
                       handleError(errorCode);
                      }
                      errrCount =   errrCount+1;
                      nfcManager.unTouchIcOpenHead();
                }
            },
        1000);


    }


     private void initNFC() {
               Log.d(TAG,"initNFC");
         boolean success = nfcManager.openNFCSerial("");
         if (success) {
             nfcManager.OpenNfc();
             nfcManager.registerNFCEventListener(this);
             nfcManager.touchIcOpenHead();
             progressHandler.postDelayed(new Runnable() {
                 @Override
                 public void run() {
                     if (!openHead) {
                         Log.d(TAG,"!openHead");
                         // clickable(false);
                         // powerTextV.setText("NFC Open Head failed");
                         // powerTextV.setTextColor(getResources().getColor(android.R.color.holo_red_dark));
                     }
                 }
             }, 2000);
         } else {
                Log.d(TAG,"initNFC");
             // clickable(false);
             // powerTextV.setText("NFC open failed");
             // powerTextV.setTextColor(getResources().getColor(android.R.color.holo_red_dark));
         }
     }


    @Override
    public void onInitCard() {
           Log.d(TAG,"onInitCard");
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                // initCardInfoTextV.setVisibility(View.VISIBLE);
                // initCardBtn.setVisibility(View.GONE);
            }
        });
    }

    private void handleError(final int staCodeValue) {
             Log.d(TAG,"handleError--staCodeValue--"+staCodeValue);

        runOnUiThread(new Runnable() {
            @Override
            public void run() {


                String[] cardIds = new String[10];
                Message readMsg = new Message();
                readMsg.what = READ_RESPONSE;
                Bundle readBundle = new Bundle();
                cardIds[0] ="error";
                readBundle.putStringArray("cardId", cardIds);
                readMsg.setData(readBundle);
                IminPrinter.getNfcEventHandler().sendMessage(readMsg);
                finish();


                // showDialog("staCodeError", NFCErrorState.getErrorDes(staCodeValue) + "---staCodeValue: 0x" + Integer.toHexString(staCodeValue));
            }
        });
}
    private void handleSearchCard(final String cardId) {

      // nfcManager.unTouchIcCloseHead();

      // String[] cardIds = new String[10];
      // Message readMsg = new Message();
      // readMsg.what = READ_RESPONSE;
      // Bundle readBundle = new Bundle();
      // cardIds[0] = cardId;
      // readBundle.putStringArray("cardId", cardId);
      // readMsg.setData(readBundle);
      // IminPrinter.getNfcEventHandler().sendMessage(readMsg);
      // finish();

    runOnUiThread(new Runnable() {
        @Override
        public void run() {

            if (cardId != null && cardId.isEmpty()) {
                // showDialog(OperationDes.OPERATION_SEARCH_CARD_DES + "  failed ", "");
                    Log.d(TAG,"failed");
            } else {
                  Log.d(TAG,"card Id is "+cardId);


                  String[] cardIds = new String[10];
                  Message readMsg = new Message();
                  readMsg.what = READ_RESPONSE;
                  Bundle readBundle = new Bundle();
                  cardIds[0] = cardId;
                  readBundle.putStringArray("cardId", cardIds);
                  readMsg.setData(readBundle);
                    nfcManager.unTouchIcCloseHead();
                  IminPrinter.getNfcEventHandler().sendMessage(readMsg);
                  finish();
                // showDialog(OperationDes.OPERATION_SEARCH_CARD_DES + "  success ", "cardId--" + cardId);
            }


        }
    });

}

}
