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

using System.Runtime.InteropServices;

namespace UCBioBSP.NET_AuditFIRDemo
{
    public partial class Form1 : Form
    {
        [DllImport("msvcrt.dll", EntryPoint = "memcpy", CallingConvention = CallingConvention.Cdecl, SetLastError = false)]
        public static extern IntPtr memcpy(IntPtr dest, IntPtr src, UIntPtr count);
        [DllImport("msvcrt.dll", EntryPoint = "memcpy", CallingConvention = CallingConvention.Cdecl, SetLastError = false)]
        static extern IntPtr fopen(String filename, String mode);
        [DllImport("msvcrt.dll", EntryPoint = "memcpy", CallingConvention = CallingConvention.Cdecl, SetLastError = false)]
        static extern IntPtr fwrite(byte[] buffer, IntPtr size, IntPtr number, IntPtr file);



        UCBioAPI m_UCBioAPI;
        UCBioAPI.Export m_Export;

        UCBioAPI.Type.INIT_INFO_0 m_InitInfo0;

        public Form1()
        {
            InitializeComponent();
            m_UCBioAPI = new UCBioAPI();
            m_Export = new UCBioAPI.Export(m_UCBioAPI);
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            /*
             //기존 파일 바이트 배열 및 이미지 변환 소스
            FolderBrowserDialog fd = new FolderBrowserDialog();

            if (fd.ShowDialog() == DialogResult.OK)
            {
                string szPath = string.Format("{0}\\0-0.bmp", fd.SelectedPath);

                using (Bitmap SampleImage = (Bitmap)Image.FromFile(szPath))
                {
                    byte[] temp = imageToByteArray(SampleImage, System.Drawing.Imaging.ImageFormat.Bmp);
                    //WriteBitmapFile(szPath.Replace("0-0.bmp", "0-1.bmp"), 256, 292, temp);
                                        

                    FileStream fs = File.OpenRead(szPath);
                    byte[] tbuf = new byte[fs.Length];
                    fs.Read(tbuf, 0, (int)fs.Length);

                    string s = null;
                    for (int i = 0; i < 2000; i++)
                    {
                        s += tbuf[i].ToString() + Environment.NewLine;
                    }

                    Image im = byteArrayToImage(temp);
                    im.Save(szPath.Replace("0-0.bmp", "0-1.bmp"));
                    pictureBox1.Image = im;

                    File.WriteAllBytes(szPath.Replace("0-0.bmp", "0-1.bmp"), temp);
                    File.WriteAllBytes(szPath.Replace("0-0.bmp", "0-2.bmp"), tbuf);

                }
            }
            
            */

            if (m_UCBioAPI.GetInitInfo(out m_InitInfo0) == UCBioAPI.Error.NONE)
            {
                UCBioAPI.Type.VERSION version = new UCBioAPI.Type.VERSION();
                m_UCBioAPI.GetVersion(out version);
                Text = String.Format("UCBioBSP_AuditFIRDemo.NET with C# (BSP Version : v{0}.{1:D4})", version.Major, version.Minor);

            }
        }
        
        private void btnAuditToImage_Click(object sender, EventArgs e)
        {
            short iDeviceID = UCBioAPI.Type.DEVICE_ID.AUTO;
            uint ret = m_UCBioAPI.OpenDevice(iDeviceID);
            if (ret != UCBioAPI.Error.NONE)
            {
                MessageBox.Show("Device open failed", "Fail", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }
            try
            {
                UCBioAPI.Type.HFIR hCapturedFIR = new UCBioAPI.Type.HFIR();
                UCBioAPI.Type.HFIR hAuditFIR = new UCBioAPI.Type.HFIR();
                ret = this.m_UCBioAPI.Capture(UCBioAPI.Type.FIR_PURPOSE.AUDIT, out hCapturedFIR, UNIONCOMM.SDK.UCBioBSP.UCBioAPI.Type.TIMEOUT.DEFAULT, hAuditFIR, null);
                if (ret == UCBioAPI.Error.NONE)
                {
                    UCBioAPI.Type.INPUT_FIR inputFIR = new UCBioAPI.Type.INPUT_FIR();
                    inputFIR.Form = UCBioAPI.Type.INPUT_FIR_FORM.HANDLE;
                    inputFIR.InputFIR.FIRinBSP = hAuditFIR;

                    UCBioAPI.Export.EXPORT_AUDIT_DATA ExportAuditData = new UCBioAPI.Export.EXPORT_AUDIT_DATA();
                    ret = this.m_Export.AuditFIRToImage(inputFIR, out ExportAuditData);
                    if (ret == UCBioAPI.Error.NONE)
                    {
                        FolderBrowserDialog fd = new FolderBrowserDialog();

                        if (fd.ShowDialog() == DialogResult.OK)
                        {
                            for (int i = 0; i < ExportAuditData.FingerNum; i++)
                            {
                                for (int j = 0; j < ExportAuditData.SamplesPerFinger; j++)
                                {
                                    string szPath = string.Format("{0}\\{1}-{2}.bmp", fd.SelectedPath, ExportAuditData.AuditData[i].FingerID, j);
                                    SaveBMP(szPath, ExportAuditData.AuditData[i].Image[j].Data, ExportAuditData.ImageWidth, ExportAuditData.ImageHeight, ExportAuditData.ImageWidth * ExportAuditData.ImageHeight);
                                    szPath = szPath.Replace("bmp", "raw");
                                    FileStream rm = new FileStream(szPath, FileMode.Create);
                                    rm.Write(ExportAuditData.AuditData[i].Image[j].Data, 0, (int)(ExportAuditData.ImageWidth * ExportAuditData.ImageHeight));
                                    rm.Close();
                                    //File.WriteAllBytes(szPath, iRawDataq);

                                }
                            }
                        }
                    }
                    inputFIR = null;
                }
                else
                    MessageBox.Show("Matching failed", "Fail", MessageBoxButtons.OK, MessageBoxIcon.Information);

                hCapturedFIR = null;
                hAuditFIR = null;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString(), "Fail", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            finally
            {
                this.m_UCBioAPI.CloseDevice(UCBioAPI.Type.DEVICE_ID.AUTO);
            }
        }

        private void SaveBMP(string filePath, byte[] iRawDataq, uint imgWidth, uint imgHeight, uint length)
        {
            try
            {
                txtWidth.Text = imgWidth.ToString();
                txtHeight.Text = imgHeight.ToString();

                // 이미지 헤더 만들기
                byte[] imgBuf = new byte[length+1078];
                byte[] tempBuf = new byte[100000];

                BITMAPFILEHEADER bitHeader = new BITMAPFILEHEADER();
                bitHeader.bfType = ((ushort)('M' << 8) | 'B');
                bitHeader.bfSize = imgWidth * imgHeight + 1078;
                bitHeader.bfOffBits = 1078;

                tempBuf = StructToByte(bitHeader);
                int bitFileHeaderSize = Marshal.SizeOf(bitHeader);

                int i = 0;
                int j = 0;
                for (i = 0; i < bitFileHeaderSize; i++)
                {
                    imgBuf[i] = tempBuf[i];
                }

                BITMAPINFOHEADER bitInfoHeader = new BITMAPINFOHEADER();
                bitInfoHeader.biSize = (uint)Marshal.SizeOf(bitInfoHeader); ;
                bitInfoHeader.biWidth = (int)imgWidth;
                bitInfoHeader.biHeight = (int)imgHeight;
                bitInfoHeader.biPlanes = 1;
                bitInfoHeader.biBitCount = 8;
                bitInfoHeader.biCompression = (uint)0L;
                bitInfoHeader.biSizeImage = imgWidth * imgHeight;
                bitInfoHeader.biXPelsPerMeter = 2834;
                bitInfoHeader.biYPelsPerMeter = 2834;
                bitInfoHeader.biClrUsed = 256;
                bitInfoHeader.biClrImportant = 256;

                tempBuf = StructToByte(bitInfoHeader);
                int bitInfoHeaderSize = Marshal.SizeOf(bitInfoHeader);
                j = 0;
                for (i = bitFileHeaderSize; i < bitFileHeaderSize + bitInfoHeaderSize; i++)
                {
                    imgBuf[i] = tempBuf[j++];
                }

                i = 0;
                j = 0;
                RGBQUAD[] bmiColors = new RGBQUAD[256];
                for (i = 0; i < 256; i++)
                {
                    bmiColors[i].rgbRed = (byte)i;
                    bmiColors[i].rgbGreen = (byte)i;
                    bmiColors[i].rgbBlue = (byte)i;
                    bmiColors[i].rgbReserved = 0xff;// 0;
                }
                RGBQUAD rgb = new RGBQUAD();
                int rgbQuadSize = 256 * Marshal.SizeOf(rgb);
                j = 0;
                for (i = bitFileHeaderSize + bitInfoHeaderSize; i < rgbQuadSize + bitFileHeaderSize + bitInfoHeaderSize; i = i + 4)
                {
                    imgBuf[i] = (byte)j;
                    imgBuf[i + 1] = (byte)j;
                    imgBuf[i + 2] = (byte)j++;
                    imgBuf[i + 3] = 0;

                }
                // 이미지 헤더 만들기 끝

                // 로우 이미지 뒤집기 
                //j = 0;
                //int k=0;
                //for (i = (int)imgHeight - 1; i >= 0;i-- )
                //{
                //    for (j = bitFileHeaderSize + bitInfoHeaderSize + rgbQuadSize + (j * (int)imgWidth); j < (int)imgWidth + bitFileHeaderSize + bitInfoHeaderSize + rgbQuadSize + (i * (int)imgWidth); j++)
                //    {
                //        imgBuf[j] = iRawDataq[i * imgWidth];
                //    }
                //}

                // 로우 이미지 넣기 (배열1078부터)
                //                 j = 0;
                //                 for (i = bitFileHeaderSize + bitInfoHeaderSize + rgbQuadSize; i < bitFileHeaderSize + bitInfoHeaderSize + rgbQuadSize + length;i++ )
                //                 {
                //                     imgBuf[i] = iRawDataq[j++];
                //                 }

                // 로우 이미지 뒤집어 넣기
                j = bitFileHeaderSize + bitInfoHeaderSize + rgbQuadSize;
                for (i = (int)length - 1; i > 0; i--)
                {
                    imgBuf[j++] = iRawDataq[i];
                }
                // 파일로 쓰기
                File.WriteAllBytes(filePath, imgBuf);
                // 이미지 표출
                Image im = byteArrayToImage(imgBuf);
                pictureBox1.Image = im;



                //WriteBitmapFile(filePath, (int)imgWidth, (int)imgHeight, iRawDataq);
                //WriteBitmapFile(filePath, (int)imgWidth, (int)imgHeight, imgBuf);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString(), "Fail", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
        }

        public static byte[] StructToByte(object st)
        {
            int size = Marshal.SizeOf(st);
            byte[] buffer = new byte[Marshal.SizeOf(st)];
            unsafe
            {
                fixed (byte* fixed_buffer = buffer)
                {
                    Marshal.StructureToPtr(st, (IntPtr)fixed_buffer, false);
                }
            }
            return buffer;
        }

        private static Image ByteArrayToImage(byte[] b)
        {
            ImageConverter imgcvt = new ImageConverter();
            System.Drawing.Image img = (System.Drawing.Image)imgcvt.ConvertFrom(b);
            return img;
        }

        private static byte[] ImageToByteArrary(System.Drawing.Image img)
        {
            ImageConverter imgcvt = new ImageConverter();
            byte[] b = (byte[])imgcvt.ConvertTo(img, typeof(byte[]));
            return b;
        }
        /// ///////////////////////
        public byte[] imageToByteArray(Image imageIn, System.Drawing.Imaging.ImageFormat imageformat)
        {
            MemoryStream ms = new MemoryStream();
            imageIn.Save(ms, imageformat);
            return ms.ToArray();
        }

        public Image byteArrayToImage(byte[] byteArrayIn)
        {
            MemoryStream ms = new MemoryStream(byteArrayIn);
            Image returnImage = Image.FromStream(ms);
            return returnImage;

        }

        int WriteBitmapFile(string filename, int width, int height, byte[] imageData)
        {
            //using (MemoryStream stream = new MemoryStream(imageData))
            using (Bitmap bmp = new Bitmap(width, height, System.Drawing.Imaging.PixelFormat.Format24bppRgb))
            {
                System.Drawing.Imaging.BitmapData bmpData = bmp.LockBits(new Rectangle(0, 0, bmp.Width, bmp.Height), System.Drawing.Imaging.ImageLockMode.WriteOnly, bmp.PixelFormat);
                System.Runtime.InteropServices.Marshal.Copy(imageData, 0, bmpData.Scan0, imageData.Length);
                bmp.UnlockBits(bmpData);
                bmp.Save(filename);
            }
            return 1;

            //                 unsafe
            //                 {
            //                     fixed (byte* ptr = iRawDataq)
            //                     {
            //                         using (Bitmap image = new Bitmap((int)imgWidth, (int)imgHeight, (int)(imgWidth * 3), System.Drawing.Imaging.PixelFormat.Format24bppRgb, new IntPtr(ptr)))
            //                         {
            //                             image.Save(filePath);
            //                         }                        
            //                     }
            //                 }


            //                 using (Bitmap SampleImage = (Bitmap)Image.FromFile(filePath))
            //                 {
            //                     pictureBox1.Image = SampleImage;
            //                 }

        }

                /*
        /// <summary>
        /// This structure contains information about the type, size, and layout of a file that containing a device-independent bitmap (DIB).
        /// </summary>
        /// <remarks>Wraps the native <b>BITMAPFILEHEADER</b> structure</remarks>
        public class BitmapFileHeader
        {
            private byte[] data;

            public BitmapFileHeader()
            {
                data = new byte[14];
            }
            /// <summary>
            /// Specifies the file type. It must be BM.
            /// </summary>
            public short Type
            {
                get { return BitConverter.ToInt16(data, 0); }
                set { BitConverter.GetBytes(value).CopyTo(data, 0); }
            }
            /// <summary>
            /// Specifies the size, in bytes, of the bitmap file.
            /// </summary>
            public int Size
            {
                get { return BitConverter.ToInt32(data, 2); }
                set { BitConverter.GetBytes(value).CopyTo(data, 2); }
            }

            //public ushort  bfReserved1;
            //public ushort  bfReserved2; 
            /// <summary>
            /// Specifies the offset, in bytes, from the <b>BitmapFileHeader</b> structure to the bitmap bits.
            /// </summary>
            public int OffBits
            {
                get { return BitConverter.ToInt32(data, 10); }
                set { BitConverter.GetBytes(value).CopyTo(data, 10); }
            }

            public byte[] Data { get { return data; } }
        }
        */

        [StructLayout(LayoutKind.Sequential, Pack = 1)]
        public struct BITMAPFILEHEADER
        {
            public ushort bfType;
            public uint bfSize;
            public ushort bfReserved1;
            public ushort bfReserved2;
            public int bfOffBits;
        }


        [StructLayout(LayoutKind.Sequential)]
        public struct BITMAPINFOHEADER
        {
            public uint biSize;
            public int biWidth;
            public int biHeight;
            public ushort biPlanes;
            public ushort biBitCount;
            public uint biCompression;
            public uint biSizeImage;
            public int biXPelsPerMeter;
            public int biYPelsPerMeter;
            public uint biClrUsed;
            public uint biClrImportant;

            public void Init()
            {
                biSize = (uint)Marshal.SizeOf(this);
            }
        }


        [StructLayout(LayoutKind.Sequential, Pack = 1)]
        public struct RGBQUAD
        {
            public Byte rgbBlue;
            public Byte rgbGreen;
            public Byte rgbRed;
            public Byte rgbReserved;
        }

        [StructLayout(LayoutKind.Sequential)]
        public struct LPBITMAPINFO
        {
            public BITMAPINFOHEADER bmiHeader;
            public RGBQUAD[] bmiColors;
        }


        private void btnImageToAudit_Click(object sender, EventArgs e)
        {
            OpenFileDialog openFileDlg = new OpenFileDialog();
            openFileDlg.Filter = "bin files(*.raw)|*.raw|All file(*.*)|*.*";
            if (openFileDlg.ShowDialog() == DialogResult.OK)
            {
                FileInfo file = new FileInfo(openFileDlg.FileName);

                if (file.Length == (Convert.ToInt32(txtWidth.Text) * Convert.ToInt32(txtHeight.Text)))
                {

                    short iDeviceID = UCBioAPI.Type.DEVICE_ID.AUTO;
                    uint ret = m_UCBioAPI.OpenDevice(iDeviceID);
                    if (ret != UCBioAPI.Error.NONE)
                    {
                        //SetStatusText("Failed to open device");
                        return;
                    }
                    try
                    {
                        UCBioAPI.Export.EXPORT_AUDIT_DATA exportAuditFIR = new UCBioAPI.Export.EXPORT_AUDIT_DATA();
                        exportAuditFIR.FingerNum = 1;
                        exportAuditFIR.SamplesPerFinger = 1;
                        exportAuditFIR.ImageWidth = Convert.ToUInt32(txtWidth.Text);
                        exportAuditFIR.ImageHeight = Convert.ToUInt32(txtHeight.Text);
                        exportAuditFIR.AuditData = new UCBioAPI.Export.AUDIT_DATA[exportAuditFIR.FingerNum];
                        exportAuditFIR.AuditData[0].FingerID = 0;
                        exportAuditFIR.AuditData[0].Image = new UCBioAPI.Export.IMAGE_DATA[exportAuditFIR.SamplesPerFinger];
                        exportAuditFIR.AuditData[0].Image[0].Data = new byte[exportAuditFIR.ImageWidth * exportAuditFIR.ImageHeight];

                        UCBioAPI.Type.HFIR hAuditFIR = null;
                        ret = this.m_Export.ImageToAuditFIR(exportAuditFIR, out hAuditFIR);
                        if (ret == UCBioAPI.Error.NONE)
                        {
                            UCBioAPI.Type.INPUT_FIR inputFIR = new UCBioAPI.Type.INPUT_FIR();
                            inputFIR.Form = UCBioAPI.Type.INPUT_FIR_FORM.HANDLE;
                            inputFIR.InputFIR.FIRinBSP = hAuditFIR;
                            UCBioAPI.Type.HFIR hNewFIR = new UCBioAPI.Type.HFIR();
                            ret = m_UCBioAPI.Process(inputFIR, out hNewFIR);
                            if (ret == UCBioAPI.Error.NONE)
                            {
                                inputFIR.Form = UCBioAPI.Type.INPUT_FIR_FORM.HANDLE;
                                inputFIR.InputFIR.FIRinBSP = hNewFIR;
                                UCBioAPI.Export.EXPORT_DATA exportData = new UCBioAPI.Export.EXPORT_DATA();
                                ret = m_Export.FIRToTemplate(inputFIR, out exportData, UCBioAPI.Type.TEMPLATE_TYPE.SIZE500);

                                UCBioAPI.Type.FIR_TEXTENCODE TextFIR = new UCBioAPI.Type.FIR_TEXTENCODE();
                                ret = m_UCBioAPI.GetTextFIRFromHandle(hNewFIR, out TextFIR, false);
                                txtTextFIR.Text = TextFIR.TextFIR;

                                string szPath = openFileDlg.FileName;
                                szPath = szPath.Replace("raw", "uct");
                                FileStream rm = new FileStream(szPath, FileMode.Create);
                                rm.Write(exportData.FingerInfo[0].Template[0].Data, 0, exportData.FingerInfo[0].Template[0].Data.Length);
                                rm.Close();

                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show(ex.ToString(), "Fail", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    }
                    finally
                    {
                        this.m_UCBioAPI.CloseDevice(UCBioAPI.Type.DEVICE_ID.AUTO);
                    }

                }
            }
        }

        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            m_Export = null;
            m_UCBioAPI.CloseDevice(UCBioAPI.Type.DEVICE_ID.AUTO);
            m_UCBioAPI = null;
        }

        private void txtTextFIR_DoubleClick(object sender, EventArgs e)
        {
            TextBox subtextBox = new System.Windows.Forms.TextBox();

            subtextBox.Location = new System.Drawing.Point(12, 12);
            subtextBox.Multiline = true;
            subtextBox.Name = "textBox1";
            subtextBox.Size = new System.Drawing.Size(486, 351);
            subtextBox.TabIndex = 0;

            Form frm = new Form();
            frm.AutoScaleDimensions = new System.Drawing.SizeF(7F, 12F);
            frm.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
            frm.ClientSize = new System.Drawing.Size(510, 375);
            frm.Controls.Add(subtextBox);
            frm.Name = "EventFrm";
            frm.Text = "EventFrm";
//             frm.ResumeLayout(false);
//             frm.PerformLayout();

            subtextBox.Text = txtTextFIR.Text;
            frm.ShowDialog();

        }

        private void pictureBox1_DoubleClick(object sender, EventArgs e)
        {
            PictureBox subPictureBox = new System.Windows.Forms.PictureBox();
//             ((System.ComponentModel.ISupportInitialize)(this.pictureBox1)).BeginInit();
//             this.SuspendLayout();
            // 
            // pictureBox1
            // 
            subPictureBox.Dock = System.Windows.Forms.DockStyle.Fill;
            subPictureBox.Location = new System.Drawing.Point(0, 0);
            subPictureBox.Name = "pictureBox1";
            subPictureBox.Size = new System.Drawing.Size(510, 375);
            subPictureBox.SizeMode = System.Windows.Forms.PictureBoxSizeMode.AutoSize;
            subPictureBox.TabIndex = 0;
            subPictureBox.TabStop = false;

            Form frm = new Form();
            frm.AutoScaleDimensions = new System.Drawing.SizeF(7F, 12F);
            frm.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
            frm.ClientSize = new System.Drawing.Size(510, 375);
            frm.Controls.Add(subPictureBox);
            frm.Name = "EventFrm";
            frm.Text = "EventFrm";
            //((System.ComponentModel.ISupportInitialize)(this.pictureBox1)).EndInit();
//             frm.ResumeLayout(false);
//             frm.PerformLayout();
            subPictureBox.Image = this.pictureBox1.Image;
            frm.ShowDialog();

        }
    }
}