using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Zebra.Sdk.Comm;
using Zebra.Sdk.Printer.Discovery;

// *************************************
// * Angel Ivan 07/Nov/2024
// *************************************

namespace ScaBox30.Controller
{
    class ZebraController
    {
        String prnfile = "";
        String prnpath = Application.StartupPath + "\\";
        string etiqueta;
        StreamReader reader;

        public ZebraController(String prnpath)
        {
            this.prnpath += prnpath;
        }


        #region ZEBRA -> initDiscovery()
        public void initDiscovery()
        {
            NetworkDiscoveryHandler discoveryHandler = new NetworkDiscoveryHandler();
            try
            {
                Console.WriteLine("Starting printer discovery.");
                NetworkDiscoverer.FindPrinters(discoveryHandler);
                while (!discoveryHandler.DiscoveryComplete)
                {
                    System.Threading.Thread.Sleep(10);
                }
            }
            catch (DiscoveryException e)
            {
                Console.WriteLine(e.ToString());
            }

        }
        #endregion

        #region ZEBRA -> buildPrn()
        public void buildPrn(String v1, String v2, String v3, String v4, DateTime v5, String barcode)
        {
            try
            {
                etiqueta = "";
                reader = new StreamReader(prnpath);
                prnfile = reader.ReadToEnd();
                reader.Close();
            }
            catch (IOException)
            {
                MessageBox.Show("No se ha podido abrir la plantilla de impresión\n" + prnpath, "Error de impresión", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }


            string[] lines = prnfile.Split(new string[] { "\r\n", "\r", "\n" }, StringSplitOptions.None);

            foreach (string line in lines)
            {
                if (line.Contains("$V1$"))
                {
                    /*Falta el dato desde master_codigos.csv posiblemente*/
                    etiqueta += v1 != null ? line.Replace("$V1$", v1) : line.Replace("$V1$", "null");
                }
                else if (line.Contains("$V2$"))
                {
                    etiqueta += v2 != null ? line.Replace("$V2$", v2) : line.Replace("$V2$", "null" + " / " + "null");
                }
                else if (line.Contains("0000000000"))
                {
                    etiqueta += !barcode.Contains("-") ? line.Replace("0000000000", barcode) : line.Replace("0000000000", "0000000000");
                }
                else if (line.Contains("$V3$"))
                {
                    etiqueta += line.Replace("$V3$", v3);
                }
                else if (line.Contains("$V4$"))
                {
                    etiqueta += line.Replace("$V4$", v4.ToString()); //consecutivo
                }
                else if (line.Contains("$V5$"))
                {
                    // Insertar fecha formateada en formato juliano (yyyyDDD)
                    int julianDay = v5.DayOfYear;
                    etiqueta += line.Replace("$V5$", $"{v5:yyyy}{julianDay:000}"); // yyyyDDD
                }
                else
                {
                    etiqueta += line;
                }


            }


        }
        #endregion

        #region ZEBRA -> SendZplOverTcp(string theIpAddress)
        public void SendZplOverTcp(string theIpAddress)
        {
            // Instantiate connection for ZPL TCP port at given address
            Connection thePrinterConn = new TcpConnection(theIpAddress, TcpConnection.DEFAULT_ZPL_TCP_PORT);

            try
            {
                // Open the connection - physical connection is established here.
                thePrinterConn.Open();

                //se obtiene la plantilla de la etiqueta y se reemplazan los valores
                //readprn();

                // This example prints "This is a ZPL test." near the top of the label.
                //string zplData = "^XA^FO20,20^A0N,25,25^FDThis is a ZPL test.^FS^XZ";
                string zplData = etiqueta;

                // Send the data to printer as a byte array.
                thePrinterConn.Write(Encoding.UTF8.GetBytes(zplData));
            }
            catch (ConnectionException e)
            {
                Console.WriteLine(e.ToString());
            }
            finally
            {
                // Close the connection to release resources.
                thePrinterConn.Close();
            }
        }
        #endregion

        #region SendZplOverUsb(string usbDriverName)
        public void SendZplOverUsb(string usbDriverName)
        {
            Connection thePrinterConn = null;
            try
            {
                // Instantiate USB connection for ZPL printer through its driver
                thePrinterConn = ConnectionBuilder.Build($"USB:{usbDriverName}");

                // Open the connection - physical connection is established here.
                thePrinterConn.Open();

                //se obtiene la plantilla de la etiqueta y se reemplazan los valores
                //readprn();

                // This example prints "This is a ZPL test." near the top of the label.
                //string zplData = "^XA^FO20,20^A0N,25,25^FDThis is a ZPL test.^FS^XZ";
                string zplData = etiqueta;

                // Send the data to printer as a byte array.
                thePrinterConn.Write(Encoding.UTF8.GetBytes(zplData));
            }
            catch (ConnectionException e)
            {
                // Handle communications error here.
                Console.WriteLine(e.ToString());
            }
            finally
            {
                // Close the connection to release resources.
                if (thePrinterConn != null)
                {
                    thePrinterConn.Close();
                }
            }
        }
        #endregion
    }

}

