package gen2wave.g2w_rp70a_iccard_demo;

import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.os.RemoteException;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import com.amarula.gen2wave.sdk.usbaccessory.AccessoryPower;
import com.gemalto.gempcsc.GemErrors;
import com.gemalto.gempcsc.GemPCSC_Reader;
import com.gemalto.gempcsc.IGemPCSC;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {
    private static String TAG = "Test2ICCard";
    private IGemPCSC gemPCSC_Service = null;
    private int sessionID = 0;
    private boolean mIsRetry = false;
    private boolean mIsBound = false;
    TextView icCardValueTxt = null, icCardStatusTxt = null, icCardIdTxt=null;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        set_smart_powerEnabled(true);
        ((Button)findViewById(R.id.btnICCardRead)).setVisibility(View.VISIBLE);
        ((Button)findViewById(R.id.btnICCardRead)).setOnClickListener(this);
        icCardValueTxt=((TextView)findViewById(R.id.tvICCardUid));
        icCardStatusTxt=((TextView)findViewById(R.id.tvICCardStatus));
        bindGemPCSC_ServiceApk();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mIsBound) {
            if (gemPCSC_Service != null && sessionID != 0) {
                try {
                    Log.d(TAG, "GemPCSC_Finalize");
                    gemPCSC_Service.GemPCSC_Finalize(sessionID);
                    gemPCSC_Service = null;
                } catch (RemoteException e) {
                    e.printStackTrace();
                }
            }

            Log.d(TAG, "unbindService");
            this.unbindService(serviceConnection);
        }
        set_smart_powerEnabled(false);
    }

    private void bindGemPCSC_ServiceApk() {

        Intent intentService = new Intent("com.gemalto.gempcsc.service.action");
        intentService.setPackage("com.gemalto.gempcsc.gempcscserviceactivity");
        this.bindService(intentService, serviceConnection, Context.BIND_AUTO_CREATE);
    }

    final ServiceConnection serviceConnection = new ServiceConnection() {
        @Override
        public void onServiceDisconnected(ComponentName name) {
            // on service disconnected
        }
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            // on service connected
            // ready to use IGemPCSC interface
            gemPCSC_Service = IGemPCSC.Stub.asInterface(service);
            mIsBound = true;
            mIsRetry = false;
        }

    };


    private void usbGetUID() {
        try {
            if (!mIsBound) {
                return;
            }
            if (mIsBound && sessionID == 0) {
                sessionID = gemPCSC_Service.GemPCSC_Initialize();
            }

            final GemPCSC_Reader[] usbReaders = gemPCSC_Service.GemPCSC_ListReaders(sessionID);
            if (usbReaders.length == 0) {
                icCardValueTxt.setText("");
                icCardStatusTxt.setText("Check Card Reader");
                return;
            }

            final byte[] ATR = gemPCSC_Service.GemPCSC_Connect(sessionID, usbReaders[0]);
            if (!gemPCSC_Service.GemPCSC_IsCardPresent(sessionID)) {
                icCardValueTxt.setText("");
                if (ATR[1] == 0) {//[65, 0]
                    icCardStatusTxt.setText("No Card");
                } else {//[65, -2]
                    icCardStatusTxt.setText("No Card");
                }
                gemPCSC_Service.GemPCSC_Disconnect(sessionID);
                gemPCSC_Service.GemPCSC_Finalize(sessionID);
                sessionID = 0;
                this.unbindService(serviceConnection);
                mIsBound = false;
                gemPCSC_Service = null;
                return;
            }
            if (GemErrors.GE_OK == gemPCSC_Service.GemPCSC_GetLastError()) {
                // display ATR...
                String strtv1 ="ATR:";
                for (int i = 0; i < ATR.length; i++) {
                    strtv1 += String.format("0x%02x ", ATR[i]);
                }
                icCardValueTxt.setText(strtv1);
                icCardStatusTxt.setText("Read OK");
            }
            boolean isRet = gemPCSC_Service.GemPCSC_Disconnect(sessionID);
            if (GemErrors.GE_OK == gemPCSC_Service.GemPCSC_GetLastError()) {
            }

        } catch (RemoteException e) {
            e.printStackTrace();
        }
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {

            case R.id.btnICCardRead: {
                if (!mIsRetry ) {
                    if (mIsBound) {
                        usbGetUID();
                    } else {
                        bindGemPCSC_ServiceApk();
                        mIsRetry = true;
                    }
                }

                break;
            }

        }
    }
    private void set_smart_powerEnabled(boolean enabled) {
        AccessoryPower.setPower(this, AccessoryPower.AccessoryType.SMARTCARD, enabled);
    }
}
