using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using AxZKFPEngXControl;
using System.Drawing.Imaging;

namespace Embarque
{
    public partial class VerificarHuella : Form
    {
        private String Ruta = System.Configuration.ConfigurationManager.AppSettings.Get("CadenaConeccion");
        policia.clsaccesodatos servidor = new policia.clsaccesodatos();
        public string __mesajeerror = "";
        DataTable Tabla_Balanza;
        //Variables Variable_ = new Variables();

        private AxZKFPEngX ZkFprint = new AxZKFPEngX();
        private bool Check;

        public VerificarHuella()
        {
            InitializeComponent();
        }

        private void VerificarHuella_Load(object sender, EventArgs e)
        {
            Controls.Add(ZkFprint);
            InitialAxZkfp();
            //fpicture.ImageLocation = Application.StartupPath + "\\imagen.png";
        }
       private void InitialAxZkfp()
        {
            try
            {

                ZkFprint.OnImageReceived += zkFprint_OnImageReceived;
                ZkFprint.OnFeatureInfo += zkFprint_OnFeatureInfo;
                //zkFprint.OnFingerTouching 
                //zkFprint.OnFingerLeaving
                ZkFprint.OnEnroll += zkFprint_OnEnroll;

                if (ZkFprint.InitEngine() == 0)
                {
                    ZkFprint.FPEngineVersion = "9";
                    ZkFprint.EnrollCount = 3;
                    deviceSerial.Text += " " + ZkFprint.SensorSN + " Count: " + ZkFprint.SensorCount.ToString() + " Index: " + ZkFprint.SensorIndex.ToString();
                    ShowHintInfo("Device successfully connected");
                }

            }
            catch (Exception ex)
            {
                ShowHintInfo("Device init err, error: " + ex.Message);
            }
        }
        private void zkFprint_OnImageReceived(object sender, IZKFPEngXEvents_OnImageReceivedEvent e)
        {
            Graphics g = fpicture.CreateGraphics();
            Bitmap bmp = new Bitmap(fpicture.Width, fpicture.Height);
            g = Graphics.FromImage(bmp);
            int dc = g.GetHdc().ToInt32();
            ZkFprint.PrintImageAt(dc, 0, 0, bmp.Width, bmp.Height);
            g.Dispose();
            fpicture.Image = bmp;
        }
        private void zkFprint_OnFeatureInfo(object sender, IZKFPEngXEvents_OnFeatureInfoEvent e)
        {

            String strTemp = string.Empty;
            if (ZkFprint.EnrollIndex != 1)
            {
                if (ZkFprint.IsRegister)
                {
                    if (ZkFprint.EnrollIndex - 1 > 0)
                    {
                        int eindex = ZkFprint.EnrollIndex - 1;
                        strTemp = "Please scan again ..." + eindex;
                    }
                }
            }
            ShowHintInfo(strTemp);
        }
        private void zkFprint_OnEnroll(object sender, IZKFPEngXEvents_OnEnrollEvent e)
        {
            if (e.actionResult)
            {


                string template = ZkFprint.EncodeTemplate1(e.aTemplate);
                txtTemplate.Text = template;
                ShowHintInfo("Registration successful. You can verify now");
                btnRegister.Enabled = false;
                btnVerify.Enabled = true;
            }
            else
            {
                ShowHintInfo("Error, please register again.");

            }
        }
        private void zkFprint_OnCapture(object sender, IZKFPEngXEvents_OnCaptureEvent e)
        {
            string template = ZkFprint.EncodeTemplate1(e.aTemplate);


            if (ZkFprint.VerFingerFromStr(ref template, txtTemplate.Text, false, ref Check))
            {
                ShowHintInfo("Verified");
            }
            else
                ShowHintInfo("Not Verified");

        }
        private void ShowHintInfo(String s)
        {
            prompt.Text = s;
        }     
        private void btnRegister_Click(object sender, EventArgs e)
        {
          ZkFprint.CancelEnroll();
            ZkFprint.EnrollCount = 3;
            ZkFprint.BeginEnroll();
            ShowHintInfo("Please give fingerprint sample.");
        }   
        private void btnClear_Click(object sender, EventArgs e)
        {
        fpicture.Image = null;
        }   
        private void btnVerify_Click_1(object sender, EventArgs e)
        {
         if (ZkFprint.IsRegister)
            {
                ZkFprint.CancelEnroll();
            }
            ZkFprint.OnCapture += zkFprint_OnCapture;
            ZkFprint.BeginCapture();
            ShowHintInfo("Please give fingerprint sample.");
        }
        byte[] ReadFile(string sPath)
        {
            //Initialize byte array with a null value initially.
            byte[] data = null;

            //Use FileInfo object to get file size.
            FileInfo fInfo = new FileInfo(sPath);
            long numBytes = fInfo.Length;

            //Open FileStream to read file
            FileStream fStream = new FileStream(sPath, FileMode.Open, FileAccess.Read);

            //Use BinaryReader to read file stream into byte array.
            BinaryReader br = new BinaryReader(fStream);

            //When you use BinaryReader, you need to supply number of bytes to read from file.
            //In this case we want to read entire file. So supplying total number of bytes.
            data = br.ReadBytes((int)numBytes);
            return data;

        }

        public void listar_(string fechainicio)
        {
            //try
            //{
                //this.__mesajeerror.ForeColor = Color.Blue;
                policia.clsaccesodatos servidor = new policia.clsaccesodatos();
                servidor.cadenaconexion = Ruta;
                if (servidor.abrirconexion() == true)
                {
                    Tabla_Balanza = servidor.consultar("[dbo].[pa_Listar_Trabajador_Biometrico]", fechainicio).Tables[0];
                    if (Tabla_Balanza == null)
                    {
                        __mesajeerror = servidor.getMensageError();
                        servidor.cerrarconexion();
                        MessageBox.Show(__mesajeerror, "Balanza de Camiones", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                    }
                    else
                    {
                        int NroFilas = Tabla_Balanza.Rows.Count;
                        if (NroFilas == 0)
                        {
                            servidor.cerrarconexion();
                            //this.dgvlista.DataSource = Tabla_Balanza;
                            //this.mesajeerror.Text = "NO HAY DATOS PARA MOSTRAR";
                            //this.mesajeerror.ForeColor = Color.Red;
                        }
                        else
                        {
                            ////=========================================================================
                            byte[] imageData = (byte[])Tabla_Balanza.Rows[0].ItemArray[0];
                            //FileStream f = File.OpenWrite(Server.MapPath("Imagenes") + "\\foto.jpg");
                            //f.Write((byte[])Tabla_Balanza.Rows[0].ItemArray[0], 0, ((byte[])Tabla_Balanza.Rows[0].ItemArray[0]).Length);
                            //f.Close();
                            //fpicture.ImageUrl = "~\\Imagenes\\foto.jpg"; 

                            //Initialize image variable
                            Image newImage;
                            //Read image data into a memory stream
                            using (MemoryStream ms = new MemoryStream(imageData, 0, imageData.Length))
                            {
                                ms.Write(imageData, 0, imageData.Length);
                                //Set image variable value using memory stream.
                                newImage = Image.FromStream(ms, true);
                            }
                            //set picture
                            fpicture.Image = newImage;
                            txtruta.Text = Tabla_Balanza.Rows[0].ItemArray[1].ToString();
                            //this.txtruta.Text = Tabla_Balanza.Rows[0].ItemArray[1].ToString().Length.ToString();
                            servidor.cerrarconexion();
                            ////=========================================================================
                        }

                        //this.dgvlista.Columns.Remove("Id Comision");
                        //this.dgvlista.Columns.Remove("Descripcion");
                        //this.dgvlista.Columns.Remove("Id Factura");
                        //this.dgvlista.Columns.Remove("Fecha Emision");
                        ////this.dgvlista.Columns.for("Fecha Pago").DefaultCellStyle.Format = "dd/MM/yyyy";
                    }
                }
                else
                {
                    __mesajeerror = servidor.getMensageError();
                    servidor.cerrarconexion();
                    MessageBox.Show(__mesajeerror, "Balanza de Camiones", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            //}
            //catch (Exception)
            //{
            //    MessageBox.Show("Ingrese Fecha a Buscar", "Balanza de Camiones", MessageBoxButtons.OK, MessageBoxIcon.Error);
            //    //dtpfin.Focus();
            //}
          
        }

        //public byte[] CargarImagen(string sql)
        //{   
        //    //String Ruta = System.Configuration.ConfigurationManager.AppSettings.Get("CadenaConeccion");       
        //    Ruta con = new Ruta();
        //    return con.CargarImagen(sql);
        //}

        //public static Image ByteArrayToImage(byte[] byteArrayIn)
        //{
        //    MemoryStream ms = new MemoryStream(byteArrayIn);
        //    return Image.FromStream(ms);
        //}

        //public static byte[] ImageToByteArray(Image imageIn)
        //{
        //    MemoryStream ms = new MemoryStream();
        //    imageIn.Save(ms, ImageFormat.Jpeg);
        //    return ms.ToArray();
        //}

        private void BtnBuscar_Click(object sender, EventArgs e)
        {
           
            listar_("48");
            ////byte[] datos = (byte[])row[campo imagen];
            ////fpicture.Image =ImageHelper.ByteArrayToImage(datos);
            //lusuario xx = new lusuario();
            //byte[] buffer = xx.CargarImagen(Tabla_Balanza.Rows[0].ItemArray[0].ToString());
            //if (buffer != null)
            //{
            //    Bitmap imagen = new Bitmap(new System.IO.MemoryStream(buffer));
            //    fpicture.Image = imagen;
            //    //buffer = buffer;
            //}
            
        }

        private void btnRegister_Click_1(object sender, EventArgs e)
        {

        }
    }
    
}
