using irisPrint.service;
using System;
using System.Net;
using System.Net.Sockets;
using System.Threading;

namespace irisPrint.Impl
{
    public class PrintHelper: PrintInterface
    {
        private Socket socketClient;

        public void Print(String iDCardNo, String deviceSN, String destIP, String destPort)
        {
            string info = CreateInfo(iDCardNo, deviceSN, "");

            PrintParam printParam = new PrintParam(info, destIP, destPort);
            SendInfo(printParam);
        }


        private void SendInfo(PrintParam printParam)
        {
            Thread sendThread = new Thread(new ParameterizedThreadStart(SendInfoFunction));
            sendThread.Start(printParam);
        }


        private void SendInfoFunction(object Msg)
        {
            try
            {
                PrintParam msg = (PrintParam)Msg;

                IPEndPoint endpoint = new IPEndPoint(IPAddress.Parse(msg.DestIP), Convert.ToInt32(msg.DestPort));
                socketClient = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

                socketClient.Connect(endpoint);
                if (socketClient.Connected)
                {
                    byte[] msgbytes = System.Text.Encoding.Default.GetBytes(msg.Info);
                    int i = Net.SendData(socketClient, msgbytes, -1);
                    if (i == 0)
                    {
                        socketClient.Close();
                    }
                    else
                    {

                    }
                }
            }
            catch (Exception ex)
            {

            }

        }

        private string CreateInfo(string IDCardNo, string deviceSN, string errorMsg)
        {
            string newIDCardNo = "";

            //发送真实身份证号
            if (IDCardNo != "" && IDCardNo != null)
            {
                newIDCardNo = IDCardNo;
            }
            else
            {
                newIDCardNo = "IDCardNoIsNull";
            }

            string info = "<Info><SFZH>" + newIDCardNo + "</SFZH><Flag>" + deviceSN + "</Flag><Error>" + errorMsg + "</Error></Info>";
            return info;
        }


    }
}
