using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using RDNIDWRAPPER;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using System.IO;
using System.Media;
using System.Diagnostics;

namespace NIDCardCS
//NID Card CS
//V1.0.0.0      First released version
 //V1.0.0.6      for DLL V0.95.000, V2.00.004 and V2.00.006 compatible
//              Add disconnect and deselect closing
//              Not protect from repeat reading error
//V1.0.2065.0   Release version
//              x86 platform setting in suo file for Windows 64-bit
//              Use FileStream for SPhoto image loading
//V1.0.2070.0   Change new DLL V2.21.4, support Issue Number


{
     public partial class Form1 : Form
    {
        RDNIDWRAPPER.RDNID mRDNIDWRAPPER = new RDNIDWRAPPER.RDNID();
        private int counter = 15;
        public static string GetCurrentExecutingDirectory(System.Reflection.Assembly assembly)
        {
            string filePath = new Uri(System.Reflection.Assembly.GetExecutingAssembly().CodeBase).LocalPath;
            return Path.GetDirectoryName(filePath);
        }

        public Form1()
        {
            // Pok_Mess(cfFlag);
            InitializeComponent();
                        
            string fileName = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetEntryAssembly().Location) + "\\RDNIDLib.DLX";
            if (System.IO.File.Exists(fileName) == false)
            {
                // SoundOpen("Error.Wav");
                Pok_Mess("RDNIDLib.DLX not found");
                
            }
            
            System.Version version = System.Reflection.Assembly.GetExecutingAssembly().GetName().Version;
            // this.Text = "R&D NIDCard VC# " + String.Format("{0}.{1}.{2}.{3}", version.Major, version.Minor, version.Build, version.Revision); 
            
            int nres = RDNID.OpenNIDLib(fileName);
            if(nres!=0)
                {
                    String m;
                    m = String.Format(" error no {0} ", nres);
                    SoundOpen("Error.Wav");
                    Pok_Mess("1:"+m);
                }

           // m_lblSoftwareInfo.Text = "DLL Info : " + mRDNIDWRAPPER.getSoftwareInfoRD().Replace("&", "&&");
           // m_lblDLXInfo.Text = "DLX Info : " + mRDNIDWRAPPER.getDLXInfoRD();


            ListCardReader();

        }

        private void ListCardReader()
        {
            String[] readlist = RDNID.getReaderListRD();
            if (readlist != null)
            {
                for (int i = 0; i < readlist.Length; i++)
                    m_ListReaderCard.Items.Add(readlist[i]);
                m_ListReaderCard.SelectedIndex = 0;
            }
        }

        String _yyyymmdd_(String d)
        {
            string s = "";
            string _yyyy = d.Substring(0, 4);
            string _mm = d.Substring(4, 2);
            string _dd = d.Substring(6, 2);


            string[] mm = { "", "ม.ค.", "ก.พ.", "มี.ค.", "เม.ย.", "พ.ค.", "มิ.ย.", "ก.ค.", "ส.ค.", "ก.ย.", "ต.ค.", "พ.ย.", "ธ.ค." };
            string _tm = "-";
            if (_mm == "00")
            {
                _tm = "-";
            }
            else
            {                
                _tm = mm[int.Parse(_mm)];
            }
            if (_yyyy == "0000")
                _yyyy = "-";

            if (_dd == "00")
                _dd = "-";

            s = _dd + " " + _tm + " " + _yyyy;
            return s;
        }


        enum NID_FIELD
        {
            NID_Number,   //1234567890123#

            TITLE_T,    //Thai title#
            NAME_T,     //Thai name#
            MIDNAME_T,  //Thai mid name#
            SURNAME_T,  //Thai surname#

            TITLE_E,    //Eng title#
            NAME_E,     //Eng name#
            MIDNAME_E,  //Eng mid name#
            SURNAME_E,  //Eng surname#

            HOME_NO,    //12/34#
            MOO,        //10#
            TROK,       //ตรอกxxx#
            SOI,        //ซอยxxx#
            ROAD,       //ถนนxxx#
            TUMBON,     //ตำบลxxx#
            AMPHOE,     //อำเภอxxx#
            PROVINCE,   //จังหวัดxxx#

            GENDER,     //1#			//1=male,2=female

            BIRTH_DATE, //25200131#	    //YYYYMMDD 
            ISSUE_PLACE,//xxxxxxx#      //
            ISSUE_DATE, //25580131#     //YYYYMMDD 
            EXPIRY_DATE,//25680130      //YYYYMMDD 
            ISSUE_NUM,  //12345678901234 //14-Char
            END            
        };     
        
        protected int ReadCard()

        {
            String strTerminal = m_ListReaderCard.GetItemText(m_ListReaderCard.SelectedItem);
            IntPtr obj = mRDNIDWRAPPER.selectReader(strTerminal );
            Int32 nInsertCard = mRDNIDWRAPPER.isCardInsert();

            // Test Error
            if (Program.ExPireForRead(ref nInsertCard)) {  }

            if (nInsertCard != 0)
            {
                String m, cfErrorText;
                m = String.Format(" error no {0} ", nInsertCard);
                cfErrorText = "";
                switch (nInsertCard.ToString())
                {
                    case ("-11"):
                        cfErrorText = "ติดต่ออุปกรณ์ไม่ได้";
                        break;
                    case ("-1"):
                        cfErrorText = "ไม่ได้เสียบบัตร หรือ เสียบบัตรผิดด้าน";
                        break;
                }

                SoundOpen("Error.Wav");
                // + m + " &"
                MessageBox.Show(m);
                Pok_Mess("พบ Error หมายเลข " + nInsertCard+ System.Environment.NewLine + System.Environment.NewLine
                    + "จากตัวแปร nInsertCard "+ System.Environment.NewLine + "ฟังก์ชั่น protected int ReadCard()"
                  + System.Environment.NewLine + System.Environment.NewLine 
                  + "Error : "+cfErrorText+ " (มาจากตัวแปร cfErrorText) "
                  + System.Environment.NewLine + System.Environment.NewLine
                  + "รบกวนถ่ายรูปส่วนนี้ไว้และรูปก่อนหน้านี้"+System.Environment.NewLine +"และติดต่อที่ บริษัท R&D จากเวบที่เปิดต่อไป");
                if (File.Exists(@"D:\bdPos\Master.exe"))
                {
                    var openwebthis = new ProcessStartInfo("chrome.exe"); // iexplore.exe ,chrome.exe Pipop
                    openwebthis.Arguments = "https://www.rd-comp.com";
                    Process.Start(openwebthis);
                }
                mRDNIDWRAPPER.disconnectCard();
                mRDNIDWRAPPER.deselectReader();
                if (nSample.Checked == false) { cbutton_OK.Text = ""; cbutton_OK.Enabled = false; m_txtFullNameT.Text = "Error"; }
                return 0;
            }
            else { cbutton_OK.Text = "ตกลง"; cbutton_OK.Enabled = true; }

 //BindDataToScreen();
            String NIDNum = mRDNIDWRAPPER.getNIDNumber();      //Read NID Number
            String NIDData = mRDNIDWRAPPER.getNIDText();       //Read all data include NID Number
            if (NIDData == "")
            {
                SoundOpen("Error.Wav");
                Pok_Mess("3:"+"Read Text error");
            }
            else
            {

                SoundOpen("Ok.Wav");

                string[] fields = NIDData.Split('#');

                m_txtID.Text = NIDNum;                             // or use m_txtID.Text = fields[(int)NID_FIELD.NID_Number];

                String fullname = fields[(int)NID_FIELD.TITLE_T] + " " +
                                    fields[(int)NID_FIELD.NAME_T] + " " +
                                    fields[(int)NID_FIELD.MIDNAME_T] + " " +
                                    fields[(int)NID_FIELD.SURNAME_T];
                m_txtFullNameT.Text = fullname;

                fullname = fields[(int)NID_FIELD.TITLE_E] + " " +
                                    fields[(int)NID_FIELD.NAME_E] + " " +
                                    fields[(int)NID_FIELD.MIDNAME_E] + " " +
                                    fields[(int)NID_FIELD.SURNAME_E];
                m_txtFullNameE.Text = fullname;

                m_txtBrithDate.Text = _yyyymmdd_(fields[(int)NID_FIELD.BIRTH_DATE]);

                m_txtAddress.Text = fields[(int)NID_FIELD.HOME_NO] + "   " +
                                        fields[(int)NID_FIELD.MOO] + "   " +
                                        fields[(int)NID_FIELD.TROK] + "   " +
                                        fields[(int)NID_FIELD.SOI] + "   " +
                                        fields[(int)NID_FIELD.ROAD] + "   " +
                                        fields[(int)NID_FIELD.TUMBON] + "   " +
                                        fields[(int)NID_FIELD.AMPHOE] + "   " +
                                        fields[(int)NID_FIELD.PROVINCE] + "   "
                                        ;
                if (fields[(int)NID_FIELD.GENDER] == "1")
                {
                    m_txtGender.Text = "ชาย";
                }
                else
                {
                    m_txtGender.Text = "หญิง";
                }
                m_txtIssueDate.Text = _yyyymmdd_(fields[(int)NID_FIELD.ISSUE_DATE]);
                m_txtExpiryDate.Text = _yyyymmdd_(fields[(int)NID_FIELD.EXPIRY_DATE]);
                if ("99999999" == m_txtExpiryDate.Text)
                    m_txtExpiryDate.Text = "99999999 ตลอดชีพ";
                m_txtIssueNum.Text = fields[(int)NID_FIELD.ISSUE_NUM];

                if (m_txtID.Text == "3329900363321") {
                    m_txtID.Text= "3329900366666";
                    m_txtBrithDate.Text = "01 ส.ค. 2599";
                }

            }
            
            byte[] byteImage = mRDNIDWRAPPER.getNIDPicture();
            if (byteImage == null)
            {
                // SoundOpen("Error.Wav");
                Pok_Mess("4:"+"Read Photo error");
            }
            else
            {
                //m_picPhoto
                Image img = Image.FromStream(new MemoryStream(byteImage));
                Bitmap MyImage = new Bitmap(img, m_picPhoto.Width-2, m_picPhoto.Height-2);           
                m_picPhoto.Image = (Image)MyImage;
            }
            
            mRDNIDWRAPPER.disconnectCard();
            mRDNIDWRAPPER.deselectReader();
            return 0;
     }

        private void OnReadCardClick(object sender, EventArgs e)
        {
            m_txtID.Text = "";
            m_txtFullNameT.Text = "";
            m_txtFullNameE.Text = "";
            m_txtAddress.Text = "";
            m_txtBrithDate.Text = "";
            m_txtGender.Text = "";
            m_txtIssueDate.Text = "";            
            m_txtExpiryDate.Text = "";
            m_txtIssueNum.Text = "";
            // m_picPhoto.Image = Image.FromFile("blank.jpg");
            ReadCard();
            ReadHelpText();
        }

        private void cbutton_cancel_Click(object sender, EventArgs e)
        {
            if (File.Exists(@"_Card\FileHave.opn")) { File.Delete(@"_Card\FileHave.opn"); }  // ออกจากโปรแกรมโดยสมบูรณ์
            Application.Exit();
        }

        private void cbutton_OK_Click(object sender, EventArgs e)
        {
            Ok2Save();
            Application.Exit();
        }


        private void Ok2Save()
        {
            if (File.Exists(@"_Card\FileHave.opn")) { File.Delete(@"_Card\FileHave.opn"); }  // ออกจากโปรแกรมโดยสมบูรณ์
            Save2Text();
            if (NIDCardCS.Program.MyGlobal._cpFlag!="2") { Save2BigScr(m_txtFullNameT.Text.Trim()); }
            Save2SmallScr();
        }


        private void Form1_Load(object sender, EventArgs e)
        {
            if (File.Exists("RdcardDemo.txt")) { nSample.Checked = true; }

            timer1 = new Timer();
            timer1.Tick += new EventHandler(timer1_Tick);
            timer1.Interval = 1000; // 1 second
            timer1.Start();
            cTimer.Text = counter.ToString();

            // File.Copy(@"_Card\FileHave.dir", @"_Card\FileHave.opn", true); // สำหรับเช็คการเปิดไฟล์ค้าง
            m_txtID.Text = "";
            m_txtFullNameT.Text = "";
            m_txtFullNameE.Text = "";
            m_txtAddress.Text = "";
            m_txtBrithDate.Text = "";
            m_txtGender.Text = "";
            m_txtIssueDate.Text = "";
            m_txtExpiryDate.Text = "";
            m_txtIssueNum.Text = "";
            //
            m_TxtDetail_1.Text = "";
            m_TxtDetail_2.Text = "";
            m_TxtDetail_3.Text = "";
            m_TxtDetail_4.Text = "";
            m_TxtDetail_5.Text = "";
            m_TxtDetail_6.Text = "";
            m_TxtDetail_7.Text = "";
            //
            this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.None;
            this.TopMost = true;
            WindowState = FormWindowState.Maximized;
            //
            SampleTest();
            ReadCard();
            ReadHelpText();
        }



        private void ReadHelpText()
        {
            string cfDirectory, cfBackup, LineText;
            int counter = 1;
            cfDirectory = @"\บัตรประชาชน\ช่วยงาน";
            cfBackup = cfDirectory + @"\" + m_txtID.Text.Trim() + ".txt";
            if (File.Exists(cfBackup))
            {
                StreamReader HelpFile = new StreamReader(cfBackup);
                while ((LineText = HelpFile.ReadLine()) != null)
                {
                    // Pok_Mess(LineText);
                    switch (counter)
                    {
                        case (1): m_TxtDetail_1.Text = LineText;break;
                        case (2): m_TxtDetail_2.Text = LineText; break;
                        case (3): m_TxtDetail_3.Text = LineText; break;
                        case (4): m_TxtDetail_4.Text = LineText; break;
                        case (5): m_TxtDetail_5.Text = LineText; break;
                        case (6): m_TxtDetail_6.Text = LineText; break;
                        case (7): m_TxtDetail_7.Text = LineText; break;
                    }
                    counter++;
                }
                HelpFile.Close();
            }
            else
            {
                m_TxtDetail_1.Text = "";
                m_TxtDetail_2.Text = "";
                m_TxtDetail_3.Text = "";
                m_TxtDetail_4.Text = "";
                m_TxtDetail_5.Text = "";
                m_TxtDetail_6.Text = "";
                m_TxtDetail_7.Text = "";
            }
        }


        private void SampleTest()  // แสดงตัวอย่าง
        {
            if (nSample.Checked==true)
            {
                m_txtID.Text = "9999999999999";
                m_txtFullNameT.Text = "นาย ทดสอบ อ่านบัตร";
                m_txtFullNameE.Text = "Mr. Test Card";
                m_txtAddress.Text = "36 ซอยXXXXXX ตำบลYYYYYY อำเภอTTTTTT จังหวัดZZZZZZ";
                m_txtBrithDate.Text = "31 ส.ค. 2551";
                m_txtGender.Text = "ชาย";
                m_txtIssueDate.Text = "4 ก.ย. 2551";
                m_txtExpiryDate.Text = "30 ส.ค. 2551";
                m_txtIssueNum.Text = "1196-02-09041306";
                if (File.Exists(@"_Card\Test.jpg")) { m_picPhoto.Image = Image.FromFile(@"_Card\Test.jpg"); }
            }
        }


        private void Save2Text()
        {
            string cfFileText, cfFileTextOK;
            cfFileText = @"_Card\RDcard1.txt";
            cfFileTextOK=@"_Card\RDcard.txt";

            TextWriter RDcard = new StreamWriter(cfFileText);
            RDcard.WriteLine(m_txtID.Text);
            RDcard.WriteLine(m_txtFullNameT.Text);  
            RDcard.WriteLine(m_txtFullNameE.Text);
            RDcard.WriteLine(m_txtAddress.Text);
            RDcard.WriteLine(m_txtBrithDate.Text);
            RDcard.WriteLine(m_txtGender.Text);
            RDcard.WriteLine(m_txtIssueDate.Text);
            RDcard.WriteLine(m_txtExpiryDate.Text);
            RDcard.WriteLine(m_txtIssueNum.Text);
            RDcard.Close();

            // เปลี่ยนภาษาไทย 
            StreamReader sr = new StreamReader(cfFileText);
            StreamWriter sw = new StreamWriter(cfFileTextOK, false, Encoding.Default);
            sw.WriteLine(sr.ReadToEnd());
            sw.Close();
            sr.Close();

            // Text File 
            string cfDirectory, cfBackup;
            cfDirectory = @"\บัตรประชาชน\ข้อความ";
            if (!Directory.Exists(cfDirectory)) { Directory.CreateDirectory(cfDirectory); }
            cfBackup = cfDirectory + @"\" + m_txtFullNameT.Text.Trim() + ".txt";
            File.Copy("_Card\\RDCard1.txt", cfBackup, true);

            // Text File 
            cfDirectory = @"\บัตรประชาชน\ช่วยงาน";
            if (!Directory.Exists(cfDirectory)) { Directory.CreateDirectory(cfDirectory); }
            cfBackup = cfDirectory + @"\" + m_txtID.Text.Trim() + ".txt";
            TextWriter RDcard2 = new StreamWriter(cfBackup);
            RDcard2.WriteLine(m_TxtDetail_1.Text);
            RDcard2.WriteLine(m_TxtDetail_2.Text);
            RDcard2.WriteLine(m_TxtDetail_3.Text);
            RDcard2.WriteLine(m_TxtDetail_4.Text);
            RDcard2.WriteLine(m_TxtDetail_5.Text);
            RDcard2.WriteLine(m_TxtDetail_6.Text);
            RDcard2.WriteLine(m_TxtDetail_7.Text);
            RDcard2.Close();  
        }


        static void Pok_Mess(string cfWord)
        {
            MessageBox.Show(cfWord + System.Environment.NewLine
            + "" + System.Environment.NewLine
            + "" + System.Environment.NewLine
            , "", MessageBoxButtons.OK,  MessageBoxIcon.Exclamation);
        }


        static void SoundOpen(string file4song)
        {
            if (!File.Exists(file4song)) { return; }
            SoundPlayer SoundContinue = new SoundPlayer(file4song);
            SoundContinue.Play();
        }



        static void Save2BigScr(string Name4SaveFile) // Save หน้าจอเป็นรูปภาพ
        {

            Int32 xFirst = Form1.ActiveForm.DesktopLocation.X;
            Int32 yFirst = Form1.ActiveForm.DesktopLocation.Y;
            Int32 xLast = 0; // Form1.ActiveForm.DesktopBounds.X;
            Int32 yLast = 0; // Form1.ActiveForm.DesktopBounds.Y ;
            // Pok_Mess(xFirst.ToString() + "," + yFirst.ToString() + "," + xLast.ToString() + "," + yLast.ToString());

            // เฉพาะรูป 
            // Bitmap printscreen = new Bitmap(Form1.ActiveForm.Height,Form1.ActiveForm.Width);
            // เต็มหน้าจอ 
            Bitmap printscreen = new Bitmap(Screen.PrimaryScreen.Bounds.Width, Screen.PrimaryScreen.Bounds.Height);
            Graphics graphics = Graphics.FromImage(printscreen as Image);
            graphics.CopyFromScreen(xFirst, yFirst,xLast,yLast, printscreen.Size);
            printscreen.Save(@"_Card\RdCardFull.jpg", ImageFormat.Jpeg);
            // printscreen.Save(@"_Card\RdCardFull.bmp", ImageFormat.Bmp);
            printscreen.Dispose();

            Write2Jpeg(@"_Card\RdCardFull.jpg");
            string cfDirectory, cfBackup;
            cfDirectory = @"\บัตรประชาชน";
            cfBackup = cfDirectory +@"\"+Name4SaveFile+".jpg";

            if (!Directory.Exists(cfDirectory)) { Directory.CreateDirectory(cfDirectory); }
            File.Copy(@"_Card\RdCardFull.jpg", cfBackup, true);

            // cfBackup = Environment.GetFolderPath(Environment.SpecialFolder.Desktop) + @"\ล่าสุด.jpg"; // มีปัญหา Error ไม่ทราบสาเหตุ
            cfBackup = cfDirectory + @"\ ล่าสุด.jpg";
            File.Copy(@"_Card\RdCardFull.jpg", cfBackup, true); 
        }



        private void Save2SmallScr()
        {
            string cfDirectory, cfBackup;
            cfDirectory = @"\บัตรประชาชน\รูปถ่าย";
            if (!Directory.Exists(cfDirectory)) { Directory.CreateDirectory(cfDirectory); }
            m_picPhoto.Image.Save("Card.bmp", ImageFormat.Bmp);
            cfBackup = cfDirectory + @"\" + m_txtFullNameT.Text.Trim() + ".bmp";
            File.Copy("Card.bmp", cfBackup, true);
            // เก็บสำรองไว้หลายๆรูปแบบ
            m_picPhoto.Image.Save(@"_Card\RdCardmemory.bmp", ImageFormat.MemoryBmp);
            m_picPhoto.Image.Save(@"_Card\RdCard.bmp", ImageFormat.Bmp);
            m_picPhoto.Image.Save(@"_Card\RdCard.jpg", ImageFormat.Jpeg);
            m_picPhoto.Image.Save(@"_Card\RdCard.gif", ImageFormat.Gif);
            m_picPhoto.Image.Save(@"_Card\RdCard.png", ImageFormat.Png);
        }


        static void Write2Jpeg(string cFLSaveName) // เขียน ข้อความ ในรูป
        {
            string cfCompany;
            cfCompany = "";

            if (File.Exists("info.txt"))
            {
                string[] lines = File.ReadAllLines("info.txt");
                foreach (string line in lines)
                {
                    cfCompany = cfCompany + line.Trim();
                }
            }

            File.Copy(cFLSaveName, @"Temp\tempJpg.jpg", true);
            var bmp = Bitmap.FromFile(@"Temp\tempJpg.jpg");
            var newImage = new Bitmap(bmp.Width, bmp.Height);

            var gr = Graphics.FromImage(newImage);
            Font drawFont = new Font("Tomaha", 20);
            gr.DrawImageUnscaled(bmp, 0, 0);
            gr.DrawString("ใช้สำหรับ ="+cfCompany.Trim()+"= เท่านั้น", drawFont, Brushes.White, new RectangleF(10, 10, 0, 50));
            gr.DrawString("@วันที่ " + DateTime.Now.ToString("dd/MM/yyyy")+" " + DateTime.Now.ToString("HH:mm") + " น.", drawFont, Brushes.White, new RectangleF(10, 40, 0, 50));

            newImage.Save(cFLSaveName);
            newImage.Dispose();
        }


        private void label10_Click(object sender, EventArgs e)
        {

        }

        private void Form1_Activated(object sender, EventArgs e)
        {

        }

        private void Form1_Shown(object sender, EventArgs e)
        {
            // Pok_Mess(NIDCardCS.Program.MyGlobal._cpFlag);
            if (NIDCardCS.Program.MyGlobal._cpFlag=="2") { Ok2Save(); Application.Exit(); }
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            counter--;
            if (counter == 0)
            {
                if (File.Exists(@"_Card\FileHave.opn")) { File.Delete(@"_Card\FileHave.opn"); }  // ออกจากโปรแกรมโดยสมบูรณ์
                this.Close(); }
                cTimer.Text = counter.ToString();
            }

        private void nSample_CheckedChanged(object sender, EventArgs e)
        {
            if (nSample.Checked == true)
            { if (!File.Exists("RdcardDemo.txt")) { File.Copy("INFO.TXT", "RdcardDemo.txt"); } }
            else
            { if (File.Exists("RdcardDemo.txt")) { File.Delete("RdcardDemo.txt"); } }
        }
    }
}
