using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

//using System;
using System.Runtime.InteropServices;
namespace DeviceApplication1
{
    public partial class Form1 : Form
    {
        private System.ComponentModel.IContainer components = null;

        private  MessageBoxButtons buttons = MessageBoxButtons.OKCancel;
        private bool m_bconncet = false;
        private int m_handle = 0;
        private int m_val = 1,mBlocknum=28,mBlocksize=0;
        private string m_csdata = ("");
        private string m_Data = ("12345678");
        private string sTempBlockData = "4444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444";
        private string sBlockData = "4444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444444";
        public string sReceiveData = "ReceivedReceivedReceivedReceived";
        public int iExit = 0;
        private bool IsStartRead = true;
        private bool IsDisconnect = false;

        public delegate void RFIDUidCallback(string pBuf, Int32 dataLen);
        public delegate void TextBoxDelegate();

        public delegate void RFIDBlockCallback(string pBuf, Int32 dataLen);
      //  public delegate void TextBoxDelegate();
        public RFIDBlockCallback callbackDelegateBlock;

        [DllImport("DT_rfid.dll")]
        public static extern int RFID_Connect(int port);

        [DllImport("DT_rfid.dll")]
        public static extern int RFID_Disconnect();

        [DllImport("DT_rfid.dll")]
        public static extern int RFID_GetBlockData(string rpt,int m_BlockNum);

        [DllImport("DT_rfid.dll")]
        public static extern int RFID_WriteBlockData(string rpt, int m_BlockNum);

        [DllImport("DT_rfid.dll")]
        public static extern int RFID_AddOrClrWriteBlockData(string rpt, int flag);

        [DllImport("DT_rfid.dll")]
        public static extern int RFID_GetAllBlockData(string rpt);

        [DllImport("DT_rfid.dll")]
        public static extern int RFID_GetBlockinfo(ref int mBlocknum, ref int mBlocksize);

        [DllImport("DT_rfid.dll", CharSet = CharSet.Unicode)]
        //DTRFID_API int _stdcall RFID_SetDataReceiverCallback(ScannerDataCallback revFun);
        public static extern int RFID_SetUidReceiverCallback(RFIDUidCallback revFun);

        [DllImport("DT_rfid.dll")]
        public static extern int RFID_StartReadBlock();
        [DllImport("DT_rfid.dll")]
        public static extern int RFID_StopReadBlock();

        [DllImport("DT_rfid.dll", CharSet = CharSet.Unicode)]
        //DTRFID_API int _stdcall RFID_SetDataReceiverCallback(ScannerDataCallback revBlockFun);
        public static extern int RFID_SetBlockReceiverCallback(RFIDBlockCallback revBlockFun);

        [DllImport("DT_rfid.dll")]
        public static extern int RFID_GetUID(string WstrUidDataBuf);
        [DllImport("winmm.dll", EntryPoint = "PlaySound")]
        private static extern bool PlaySound(string pszSound, IntPtr hmod, uint fdwSound);       //调用此函数
        public void gosound()
        {
            //string strPath = AppDomain.CurrentDomain.SetupInformation.ApplicationBase;
            string strPath ;
            strPath = "windows\\default.wav";
            PlaySound(strPath, IntPtr.Zero, 0);
        }

        public Form1()
        {
            InitializeComponent();
            if (System.Windows.Forms.Screen.PrimaryScreen.Bounds.Height < 480)
            {
               // MessageBox.Show("Set Callback fail");
                this.Size = new Size(236, 395);
            }
             button2.Enabled = false;
             button3.Enabled = false;
             button4.Enabled = false;
             button5.Enabled = false;
             button6.Enabled = false;
             button7.Enabled = false;
             button8.Enabled = false;
                //this.WindowState = FormWindowState.Maximized;
        }
        private int PosiInt(string Tstr)
        {

            /* char* str = new char[100];
             char* p = str;
             DWORD dwNum = WideCharToMultiByte(CP_OEMCP, NULL, Tstr, -1, NULL, 0, NULL, FALSE);
             WideCharToMultiByte(CP_OEMCP, NULL, Tstr, -1, (LPSTR)str, dwNum, NULL, FALSE);
             int i = 0;
             str = p;*/
            int len = Tstr.Length, i = 0;
            char[] pTrackData = new char[16];
            Tstr.CopyTo(0, pTrackData, 0, Tstr.Length);
            while (i < len)
            {
                if ((pTrackData[i] <= 57) && (pTrackData[i] >= 48))
                {
                }
                else
                {
                    // delete[] str;
                    // str = NULL;
                    return 0;
                }
                i++;
            }
            // delete[] str;
            // str = NULL;
            return 1;
        }
        private void button1_Click(object sender, EventArgs e)
        {
            if (m_bconncet)
            {
                if (m_handle >= 0)
                {
                    if(IsStartRead == false)
                    {
                        button8.Text = "StartRead";
                        IsStartRead = true; ;
                        textBox8.Text = "";
                        RFID_StopReadBlock();
                    }
                    RFID_Disconnect();
                    IsDisconnect = true;
                    button1.Text = "Connect";
                    m_bconncet = false;
                    button2.Enabled = false;
                    button3.Enabled = false;
                    button4.Enabled = false;
                    button5.Enabled = false;
                    button6.Enabled = false;
                    button7.Enabled = false;
                    button8.Enabled = false;
                    textBox1.Text = ""; 
                    textBox4.Text = "";
                    textBox5.Text = "";
                    textBox7.Text = "";
                    textBox6.Text = "";
                    textBox8.Text = "";
                    textBox2.Text = "0";
                    textBox5.Text = "0";
                }
            }
            else
            {
                m_handle = RFID_Connect(4);
                if (m_handle > 0)
                {

                    if (0 == RFID_GetBlockinfo(ref mBlocknum, ref mBlocksize))
                    {
                        textBox3.Text = Convert.ToString(mBlocknum);
                        textBox9.Text = Convert.ToString(mBlocksize);
                    }
                    button1.Text = "Disconnect";
                    m_bconncet = true;
                    button2.Enabled = true;
                    button3.Enabled = true;
                    button4.Enabled = true;
                    button5.Enabled = true;
                    button6.Enabled = true;
                    button7.Enabled = true;
                    button8.Enabled = true;
                    textBox2.Text = "0";
                    textBox4.Text = "";
                    textBox5.Text = "0";
                    textBox7.Text = "";
                  /*  RFIDUidCallback callbackDelegate = new RFIDUidCallback(revFun);
                    if (0 == RFID_SetUidReceiverCallback(callbackDelegate))
                    {
                        MessageBox.Show("Set Callback fail");
                    }*/
                    //MessageBox.Show("Set Callback success!");
                    callbackDelegateBlock = new RFIDBlockCallback(revBlockFun);
                    if (0 == RFID_SetBlockReceiverCallback(callbackDelegateBlock))
                    {
                        MessageBox.Show("Set Callback fail");
                    }
                  //  MessageBox.Show("Set Callback success!");
                }
            }
        }

        private void revBlockFun(string pBuf, Int32 dataLen)
        {
             sBlockData = pBuf;
             TextBoxHandle(sBlockData);
             //MessageBox.Show(pBuf);

           /* if (pBuf.Length > 0)
            {
                kevtBlock.OnKeyPress(pBuf);
            }*/
        }
        private void button3_Click(object sender, EventArgs e)
        {

            if (m_bconncet)
            {
                if (0 == RFID_GetBlockinfo(ref mBlocknum, ref mBlocksize))
                {
                    textBox3.Text = Convert.ToString(mBlocknum);
                    textBox9.Text = Convert.ToString(mBlocksize);
                }
               // textBox1.Text += sRead;
                textBox1.Text = "";
                RFID_GetUID(sReceiveData);
               // System.Threading.Thread.Sleep(200);
                textBox1.Text = sReceiveData;
               // sReceiveData = "";
            }

        }
      /*  private void revFun(string pBuf, Int32 dataLen)
        {
            sReceiveData = pBuf;
            //TextBoxHandle(sReceiveData);
        }*/

        private void TextBoxHandle(string sData)
        {
            //MessageBox.Show("zhang");
            if (!textBox8.InvokeRequired)  //如果在UI主线程操作ListBox，
            {
                textBox8.Text = sData;  //则直接进行控件操作，“与UI主线程相关联”
             //   MessageBox.Show("zhang");
            }
            else  //如果是在另一线程操作TextBox,则启用委托
            {
                if (iExit == 0)
                {
                   // MessageBox.Show("xian");
                    textBox8.Invoke(new TextBoxDelegate(TextShow));
                }
            }
        }

        private void TextShow()
        {
            //MessageBox.Show(sTempBlockData);
           // MessageBox.Show(sBlockData);
            
            if (sBlockData.CompareTo(sTempBlockData) != 0)
            {
                textBox8.Text = sBlockData;
                sTempBlockData = sBlockData;
            }
            

            //textBox1.Text += sReturn;
         //   textBox1.ScrollBars = ScrollBars.Vertical;
         //   textBox1.SelectionStart = textBox1.Text.Length;
          //  textBox1.ScrollToCaret();
        }
        private void button4_Click(object sender, EventArgs e)
        {
            m_csdata = ("");
            textBox1.Text = m_csdata;
        }

        private void button2_Click(object sender, EventArgs e)
        {
            if (m_bconncet)
            {
                if (0 == RFID_GetBlockinfo(ref mBlocknum, ref mBlocksize))
                {
                    textBox3.Text = Convert.ToString(mBlocknum);
                    textBox9.Text = Convert.ToString(mBlocksize);
                }
                string m_sBlock = textBox2.Text;
                string strblock = textBox2.Text;
                // int itime = (int)int.Parse(str);
                // if(itime == 30)
                //  MessageBox.Show(itime.ToString());
                if (PosiInt(strblock) == 0)
                {
                    MessageBox.Show("Please enter a positive integer.", "Warning", buttons, 0, 0);
                    return;
                }
                if (m_sBlock.Length == 0)
                {
                    MessageBox.Show("Input Block!", "Warning", buttons, 0, 0);
                    return;
                }
                char[] str = m_sBlock.ToCharArray();
                for(int i = 0;i < m_sBlock.Length; i++)
                {
                    if (!Char.IsNumber(str[i]))
                    {
                        MessageBox.Show("Please enter an integer number!", "Warning", buttons, 0, 0);
                        return;
                    }
                }
                int Block = Convert.ToInt32(m_sBlock);
         
                if((Block >= mBlocknum)||(Block < 0))
                {
                    MessageBox.Show("Please select the correct Block!", "Warning", buttons, 0, 0);
                    return;
                }
                /*if (m_First > 8)
                {
                    MessageBox.Show("First Block should less than eight.");
                    return;
                }
                if (m_First < 1)
                {
                    MessageBox.Show("First Block should more than zero.");
                    return;
                }
                if (m_First + m_Count > 9)
                {
                    MessageBox.Show("Count is wrong.");
                    return;
                }*/
                textBox4.Text = "";
                m_Data = "12345678";
              //  for (int i = m_First - 1; i < m_First + m_Count - 1; i++)
               // {
               // MessageBox.Show("befor RFID_GetBlockData!", "Warning", buttons, 0, 0);
                if (0 != RFID_GetBlockData(m_Data, Block))
                {
                    textBox4.Text = "No tag in the field!";
                    return;
                }
                if (m_Data.Length == 0)
                {
                    return;
                }
                    textBox4.Text += m_Data;//+ ";";
                 //   MessageBox.Show("after RFID_GetBlockData!", "Warning", buttons, 0, 0);
                //}
            }
        }

        private void button5_Click(object sender, EventArgs e)
        {
            if (m_bconncet)
            {
                if (0 == RFID_GetBlockinfo(ref mBlocknum, ref mBlocksize))
                {
                    textBox3.Text = Convert.ToString(mBlocknum);
                    textBox9.Text = Convert.ToString(mBlocksize);
                }
                string sBlock = textBox5.Text;
                string sDate = textBox7.Text;
                string strblock = textBox5.Text;
                // int itime = (int)int.Parse(str);
                // if(itime == 30)
                //  MessageBox.Show(itime.ToString());
                if (PosiInt(strblock) == 0)
                {
                    MessageBox.Show("Please enter a positive integer.", "Warning", buttons, 0, 0);
                    return;
                }
                if (sBlock.Length == 0 || sDate.Length == 0)
                {
                    MessageBox.Show("Input Block or Data!", "Warning", buttons, 0, 0);
                    return;
                }
                char[] str = sBlock.ToCharArray();
                for (int i = 0; i < sBlock.Length; i++)
                {
                    if (!Char.IsNumber(str[i]))
                    {
                        MessageBox.Show("Please enter an integer number!", "Warning", buttons, 0, 0);
                        return;
                    }
                }
                int m_Block = Convert.ToInt32(sBlock);
                if ((m_Block >= mBlocknum) || (m_Block < 0))
                {
                    MessageBox.Show("Please select the correct Block!", "Warning", buttons, 0, 0);
                    return;
                }
               // if (sDate.Length > 4)
                   m_val=RFID_WriteBlockData(sDate, m_Block);
                
                if (0 == m_val)
                    MessageBox.Show("Please enter the eight characters", "Warning", buttons, 0, 0);
                else if(-1 == m_val)
                    textBox7.Text = "No tag in the field!";
                else if (-2 == m_val)
                    MessageBox.Show("Please enter the correct character!", "Warning", buttons, 0, 0);
            }
        }

        private void button6_Click(object sender, EventArgs e)
        {
            if (m_bconncet)
            {
                if (0 == RFID_GetBlockinfo(ref mBlocknum, ref mBlocksize))
                {
                    textBox3.Text = Convert.ToString(mBlocknum);
                    textBox9.Text = Convert.ToString(mBlocksize);
                }
                string sDate = textBox6.Text;
                if (sDate.Length == 0)
                {
                    MessageBox.Show("Input Data!", "Warning", buttons, 0, 0);
                    return;
                }
                m_val= RFID_AddOrClrWriteBlockData(sDate, 1);
                if (-1 == m_val)
                    textBox6.Text = "No tag in the field!";
                else if (0 == m_val)
                    MessageBox.Show("Write Overflow!", "Warning", buttons, 0, 0);
                else if (-2 == m_val)
                    MessageBox.Show("Please enter the correct character!", "Warning", buttons, 0, 0);
                else if (-3 == m_val)
                    MessageBox.Show("Please enter the number of characters is a multiple of eight characters!", "Warning", buttons, 0, 0);
            }
        }

        private void button7_Click(object sender, EventArgs e)
        {
            if (m_bconncet)
            {
                if (0 == RFID_GetBlockinfo(ref mBlocknum, ref mBlocksize))
                {
                    textBox3.Text = Convert.ToString(mBlocknum);
                    textBox9.Text = Convert.ToString(mBlocksize);
                }
                string sDate = textBox6.Text;
                if (sDate.Length == 0)
                {
                    MessageBox.Show("Input Data!", "Warning", buttons, 0, 0);
                    return;
                }
                m_val = RFID_AddOrClrWriteBlockData(sDate, 0);
                if (-1 == m_val)
                    textBox6.Text = "No tag in the field!";
                else if (0 == m_val)
                    MessageBox.Show("Write Overflow!", "Warning", buttons, 0, 0);
                else if (-2 == m_val)
                    MessageBox.Show("Please enter the correct character!", "Warning", buttons, 0, 0);
                else if (-3 == m_val)
                    MessageBox.Show("Please enter the number of characters is a multiple of eight characters!", "Warning", buttons, 0, 0);
            }
        }

        private void button8_Click(object sender, EventArgs e)
        {
            if (m_bconncet)
            { 
                if(IsStartRead)
                {
                    if (0 == RFID_GetBlockinfo(ref mBlocknum, ref mBlocksize))
                    {
                        textBox3.Text = Convert.ToString(mBlocknum);
                        textBox9.Text = Convert.ToString(mBlocksize);
                    }
                    sTempBlockData = "";
                    sBlockData = "";
                    button8.Text = "EndRead";
                    //textBox8.Text = "";
                    IsStartRead = false;
                    RFID_StartReadBlock();
                }
                else
                {
                    if (0 == RFID_GetBlockinfo(ref mBlocknum, ref mBlocksize))
                    {
                        textBox3.Text = Convert.ToString(mBlocknum);
                        textBox9.Text = Convert.ToString(mBlocksize);
                    }
                     button8.Text = "StartRead";
                     IsStartRead = true; ;
                     textBox8.Text = "";
                     RFID_StopReadBlock();
                }
                
              /*  m_Data = "123456781234567812345678123456781234567812345678123456781234567812345678123456781234567812345678123456781234567812345678";
            
                if (0 != RFID_GetAllBlockData(m_Data))
                {
                    textBox8.Text = "No tag in the field!";
                    return;
                }
       
                textBox8.Text = m_Data;
               */
                
                    // textBox1.Text += sRead;
               // textBox8.Text = sBlockData;
              //  sBlockData = "";
            }
        }
        private void Form1_Closing(object sender, CancelEventArgs e)
        {
           // if (button1.Text == sDisconnect)
            if (!IsDisconnect)
            {
                RFID_Disconnect();
                button1.Text = "Connect";
                m_bconncet = false;
                button3.Enabled = false;
                textBox2.Text = "";
                textBox4.Text = "";
     
            }
                  //MessageBox.Show("zhang");
        }
        private void vScrollBar1_ValueChanged(object sender, EventArgs e)
        {
           // Form1.Top = -vScrollBar1.Value;
        }    
    }
}