﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using UNIONCOMM.SDK.UCBioBSP;

namespace UCBioBSP.NET_SmartCardDemoCS
{
    public partial class Form1 : Form
    {
        UCBioAPI m_UCBioAPI;
        UCBioAPI.SmartCard m_SmartCard;

        short m_nLastOpenedDeviceID = 0;

        Dictionary<int, short> m_deviceIDList;
        
        public Form1()
        {
            InitializeComponent();
            m_UCBioAPI = new UCBioAPI();
            m_SmartCard = new UCBioAPI.SmartCard(m_UCBioAPI);

            m_deviceIDList = new Dictionary<int, short>();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            UCBioAPI.Type.VERSION version = new UCBioAPI.Type.VERSION();
            m_UCBioAPI.GetVersion(out version);
            Text = String.Format("UCBioBSP_SmartCardDemo .NET with C# (BSP Version : v{0}.{1:D4})", version.Major, version.Minor);

            EnumDeviceList();
        }

        private void EnumDeviceList()
        {
            uint numDevice;
            short[] deviceID;
            UCBioAPI.Type.DEVICE_INFO_EX[] deviceInfo;
            uint ret = this.m_UCBioAPI.EnumerateDevice(out numDevice, out deviceID, out deviceInfo);
            if (ret != UCBioAPI.Error.NONE)
            {
                DisplayError("Failed to enumerate device!", ret);
                return;
            }

            int cbSetItemCount = 0;
            if (numDevice == 0)
            {
                cmbDevice.Items.Add("--NO DEVICE--");
                m_deviceIDList.Add(cbSetItemCount, UNIONCOMM.SDK.UCBioBSP.UCBioAPI.Type.DEVICE_ID.NONE);
                cbSetItemCount++;
            }

            cmbDevice.Items.Add("Auto_Detect");
            m_deviceIDList.Add(cbSetItemCount, UNIONCOMM.SDK.UCBioBSP.UCBioAPI.Type.DEVICE_ID.AUTO);
            cbSetItemCount++;

            for (int i = 0; i < numDevice; i++)
            {
                cmbDevice.Items.Add(string.Format("{0} - {1}", deviceInfo[i].Name, deviceInfo[i].Description));
                m_deviceIDList.Add(cbSetItemCount, deviceInfo[i].NameID);
                cbSetItemCount++;
            }
            cmbDevice.SelectedIndex = 0;
        }

        private void DisplayError(string msg, uint err)
        {
            MessageBox.Show(string.Format("{0} (Error : 0x{1:X})", msg, err), "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
        }

        private void cmbDevice_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (cmbDevice.SelectedIndex == UNIONCOMM.SDK.UCBioBSP.UCBioAPI.Type.DEVICE_ID.NONE && cmbDevice.Text != "Auto_Detect")
                return;

            short index = m_deviceIDList[cmbDevice.SelectedIndex];

            this.m_UCBioAPI.CloseDevice(m_nLastOpenedDeviceID);
            uint ret = this.m_UCBioAPI.OpenDevice(index);
            if (ret == UCBioAPI.Error.NONE)
            {
                m_nLastOpenedDeviceID = index;
            }
            else
            {
                DisplayError("Failed to open device!", ret);
            }
        }

        private void btnRFPowerOn_Click(object sender, EventArgs e)
        {
            btnReadBlock.Enabled = false;
            btnWriteBlock.Enabled = false;

            if (m_nLastOpenedDeviceID != UNIONCOMM.SDK.UCBioBSP.UCBioAPI.Type.DEVICE_ID.NONE)
            {
                uint ret = m_SmartCard.RFPowerOn();
                if (ret != UCBioAPI.Error.NONE)
                {
                    DisplayError("Failed to RFPowerOn!", ret);
                }
                else
                {
                    btnReadBlock.Enabled = true;
                    btnWriteBlock.Enabled = true;
                }
            }
        }

        private void btnRFPowerOff_Click(object sender, EventArgs e)
        {
            if (m_nLastOpenedDeviceID != UNIONCOMM.SDK.UCBioBSP.UCBioAPI.Type.DEVICE_ID.NONE)
            {
                uint ret = m_SmartCard.RFPowerOff();
                if (ret != UCBioAPI.Error.NONE)
                {
                    DisplayError("Failed to RFPowerOff!", ret);
                }
                else
                {
                    btnReadBlock.Enabled = false;
                    btnWriteBlock.Enabled = false;
                }
            }
        }

        private void btnReadSerial_Click(object sender, EventArgs e)
        {
            if (m_nLastOpenedDeviceID != UNIONCOMM.SDK.UCBioBSP.UCBioAPI.Type.DEVICE_ID.NONE)
            {
                byte[] ResultBuff ={ 0, 0, 0, 0 };
                uint ret = m_SmartCard.ReadSerial(out ResultBuff, UCBioAPI.SmartCard.LED_MODE.TOGGLE);
                if (ret != UCBioAPI.Error.NONE)
                {
                    DisplayError("Failed to execute!", ret);
                    txtSerial.Text = String.Format("00, 00, 00, 00");
                }
                else
                    txtSerial.Text = String.Format("{0:X2} {1:X2} {2:X2} {3:X2}", ResultBuff[0], ResultBuff[1], ResultBuff[2], ResultBuff[3]);

            }
        }

        private void btnReadBlock_Click(object sender, EventArgs e)
        {
            if (m_nLastOpenedDeviceID != UNIONCOMM.SDK.UCBioBSP.UCBioAPI.Type.DEVICE_ID.NONE)
            {
                byte nSectorNum = Convert.ToByte(txtSector.Text);
                byte nBlockNum = Convert.ToByte(txtBlock.Text);
                byte[] nKey;
                UCBioAPI.SmartCard.AUTH_MODE mode = GetAuthModeAndKey(out nKey);
                byte[] nResultBuff;

                uint ret = m_SmartCard.ReadBlock(nSectorNum, nBlockNum, out nResultBuff, nKey, mode, UCBioAPI.SmartCard.LED_MODE.TOGGLE);
                if (ret != UCBioAPI.Error.NONE)
                {
                    DisplayError("Failed to execute!", ret);
                    txtBlockData1.Text = string.Format("{0:X2}", 0);
                    txtBlockData2.Text = string.Format("{0:X2}", 0);
                    txtBlockData3.Text = string.Format("{0:X2}", 0);
                    txtBlockData4.Text = string.Format("{0:X2}", 0);
                    txtBlockData5.Text = string.Format("{0:X2}", 0);
                    txtBlockData6.Text = string.Format("{0:X2}", 0);
                    txtBlockData7.Text = string.Format("{0:X2}", 0);
                    txtBlockData8.Text = string.Format("{0:X2}", 0);
                    txtBlockData9.Text = string.Format("{0:X2}", 0);
                    txtBlockData10.Text = string.Format("{0:X2}", 0);
                    txtBlockData11.Text = string.Format("{0:X2}", 0);
                    txtBlockData12.Text = string.Format("{0:X2}", 0);
                    txtBlockData13.Text = string.Format("{0:X2}", 0);
                    txtBlockData14.Text = string.Format("{0:X2}", 0);
                    txtBlockData15.Text = string.Format("{0:X2}", 0);
                    txtBlockData16.Text = string.Format("{0:X2}", 0);

                }
                else
                {
                    if (nResultBuff.Length > 15)
                    {
                        txtBlockData1.Text = string.Format("{0:X2}", nResultBuff[0]);
                        txtBlockData2.Text = string.Format("{0:X2}", nResultBuff[1]);
                        txtBlockData3.Text = string.Format("{0:X2}", nResultBuff[2]);
                        txtBlockData4.Text = string.Format("{0:X2}", nResultBuff[3]);
                        txtBlockData5.Text = string.Format("{0:X2}", nResultBuff[4]);
                        txtBlockData6.Text = string.Format("{0:X2}", nResultBuff[5]);
                        txtBlockData7.Text = string.Format("{0:X2}", nResultBuff[6]);
                        txtBlockData8.Text = string.Format("{0:X2}", nResultBuff[7]);
                        txtBlockData9.Text = string.Format("{0:X2}", nResultBuff[8]);
                        txtBlockData10.Text = string.Format("{0:X2}", nResultBuff[9]);
                        txtBlockData11.Text = string.Format("{0:X2}", nResultBuff[10]);
                        txtBlockData12.Text = string.Format("{0:X2}", nResultBuff[11]);
                        txtBlockData13.Text = string.Format("{0:X2}", nResultBuff[12]);
                        txtBlockData14.Text = string.Format("{0:X2}", nResultBuff[13]);
                        txtBlockData15.Text = string.Format("{0:X2}", nResultBuff[14]);
                        txtBlockData16.Text = string.Format("{0:X2}", nResultBuff[15]);
                    }
                }
            }
        }

        private void btnWriteBlock_Click(object sender, EventArgs e)
        {
            if (m_nLastOpenedDeviceID != UNIONCOMM.SDK.UCBioBSP.UCBioAPI.Type.DEVICE_ID.NONE)
            {
                byte nSectorNum = Convert.ToByte(txtSector.Text);
                byte nBlockNum = Convert.ToByte(txtBlock.Text);

                byte[] nDataBuff = new byte[16];
                nDataBuff[0] = (byte)Convert.ToInt64(txtBlockData1.Text, 16);
                nDataBuff[1] = (byte)Convert.ToInt64(txtBlockData2.Text, 16);
                nDataBuff[2] = (byte)Convert.ToInt64(txtBlockData3.Text, 16);
                nDataBuff[3] = (byte)Convert.ToInt64(txtBlockData4.Text, 16);
                nDataBuff[4] = (byte)Convert.ToInt64(txtBlockData5.Text, 16);
                nDataBuff[5] = (byte)Convert.ToInt64(txtBlockData6.Text, 16);
                nDataBuff[6] = (byte)Convert.ToInt64(txtBlockData7.Text, 16);
                nDataBuff[7] = (byte)Convert.ToInt64(txtBlockData8.Text, 16);
                nDataBuff[8] = (byte)Convert.ToInt64(txtBlockData9.Text, 16);
                nDataBuff[9] = (byte)Convert.ToInt64(txtBlockData10.Text, 16);
                nDataBuff[10] = (byte)Convert.ToInt64(txtBlockData11.Text, 16);
                nDataBuff[11] = (byte)Convert.ToInt64(txtBlockData12.Text, 16);
                nDataBuff[12] = (byte)Convert.ToInt64(txtBlockData13.Text, 16);
                nDataBuff[13] = (byte)Convert.ToInt64(txtBlockData14.Text, 16);
                nDataBuff[14] = (byte)Convert.ToInt64(txtBlockData15.Text, 16);
                nDataBuff[15] = (byte)Convert.ToInt64(txtBlockData16.Text, 16);

                byte[] nKey;
                UCBioAPI.SmartCard.AUTH_MODE mode = GetAuthModeAndKey(out nKey);

                uint ret = m_SmartCard.WriteBlock(nSectorNum, nBlockNum, nDataBuff, nKey, mode, UCBioAPI.SmartCard.LED_MODE.TOGGLE);
                if (ret != UCBioAPI.Error.NONE)
                {
                    DisplayError("Failed to execute!", ret);
                }
            }
        }

        private UCBioAPI.SmartCard.AUTH_MODE GetAuthModeAndKey(out byte[] key)
        {
            key = new byte[6];
            if (rdbUseKeyA.Checked)
            {
                key[0] = (byte)Convert.ToInt64(txtKeyA1.Text, 16);
                key[1] = (byte)Convert.ToInt64(txtKeyA2.Text, 16);
                key[2] = (byte)Convert.ToInt64(txtKeyA3.Text, 16);
                key[3] = (byte)Convert.ToInt64(txtKeyA4.Text, 16);
                key[4] = (byte)Convert.ToInt64(txtKeyA5.Text, 16);
                key[5] = (byte)Convert.ToInt64(txtKeyA6.Text, 16);
                return UCBioAPI.SmartCard.AUTH_MODE.KEYA;
            }
            else
            {
                key[0] = (byte)Convert.ToInt64(txtKeyB1.Text, 16);
                key[1] = (byte)Convert.ToInt64(txtKeyB2.Text, 16);
                key[2] = (byte)Convert.ToInt64(txtKeyB3.Text, 16);
                key[3] = (byte)Convert.ToInt64(txtKeyB4.Text, 16);
                key[4] = (byte)Convert.ToInt64(txtKeyB5.Text, 16);
                key[5] = (byte)Convert.ToInt64(txtKeyB6.Text, 16);
                return UCBioAPI.SmartCard.AUTH_MODE.KEYB;
            }

        }

        private void txtKeyA1_TextChanged(object sender, EventArgs e)
        {
            if (txtKeyA1.Text.Length > 2)
                txtKeyA1.Text = txtKeyA1.Text.Remove(2, txtKeyA1.Text.Length-2);
            
            //txtKeyA1.SelectionStart = this.txtKeyA1.Text.Length;
        }

        private void txtKeyA2_TextChanged(object sender, EventArgs e)
        {
            if (txtKeyA2.Text.Length > 2)
                txtKeyA2.Text = txtKeyA2.Text.Remove(2, txtKeyA2.Text.Length - 2);
        }

        private void txtKeyA3_TextChanged(object sender, EventArgs e)
        {
            if (txtKeyA3.Text.Length > 2)
                txtKeyA3.Text = txtKeyA3.Text.Remove(2, txtKeyA3.Text.Length - 2);
        }

        private void txtKeyA4_TextChanged(object sender, EventArgs e)
        {
            if (txtKeyA4.Text.Length > 2)
                txtKeyA4.Text = txtKeyA4.Text.Remove(2, txtKeyA4.Text.Length - 2);
        }

        private void txtKeyA5_TextChanged(object sender, EventArgs e)
        {
            if (txtKeyA5.Text.Length > 2)
                txtKeyA5.Text = txtKeyA5.Text.Remove(2, txtKeyA5.Text.Length - 2);
        }

        private void txtKeyA6_TextChanged(object sender, EventArgs e)
        {
            if (txtKeyA6.Text.Length > 2)
                txtKeyA6.Text = txtKeyA6.Text.Remove(2, txtKeyA6.Text.Length - 2);
        }

        private void txtKeyB1_TextChanged(object sender, EventArgs e)
        {
            if (txtKeyB1.Text.Length > 2)
                txtKeyB1.Text = txtKeyB1.Text.Remove(2, txtKeyB1.Text.Length - 2);
        }

        private void txtKeyB2_TextChanged(object sender, EventArgs e)
        {
            if (txtKeyB2.Text.Length > 2)
                txtKeyB2.Text = txtKeyB2.Text.Remove(2, txtKeyB2.Text.Length - 2);
        }

        private void txtKeyB3_TextChanged(object sender, EventArgs e)
        {
            if (txtKeyB3.Text.Length > 2)
                txtKeyB3.Text = txtKeyB3.Text.Remove(2, txtKeyB3.Text.Length - 2);
        }

        private void txtKeyB4_TextChanged(object sender, EventArgs e)
        {
            if (txtKeyB4.Text.Length > 2)
                txtKeyB4.Text = txtKeyB4.Text.Remove(2, txtKeyB4.Text.Length - 2);
        }

        private void txtKeyB5_TextChanged(object sender, EventArgs e)
        {
            if (txtKeyB5.Text.Length > 2)
                txtKeyB5.Text = txtKeyB5.Text.Remove(2, txtKeyB5.Text.Length - 2);
        }

        private void txtKeyB6_TextChanged(object sender, EventArgs e)
        {
            if (txtKeyB6.Text.Length > 2)
                txtKeyB6.Text = txtKeyB6.Text.Remove(2, txtKeyB6.Text.Length - 2);
        }

        private void btnOK_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            this.m_UCBioAPI.CloseDevice(m_nLastOpenedDeviceID);
        }

    }
}