using MesServerFunctions;
using MesWork;
using NPOI.XWPF.UserModel;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using static System.Runtime.CompilerServices.RuntimeHelpers;

namespace MesDataFunction
{
    public class PrintTo
    {

        /// <summary>
        /// 
        /// </summary>
        /// <param name="str"></param>
        public static bool Print(bool isSinglePrint,string url,string[] strArray)
        {
            if (PP.IsDemoMesServer == 1)
            {
                var list = new List<string>();
                foreach (string str in strArray)
                {
                    var printStr = str;
                    if (isSinglePrint)
                    {
                        printStr = str.Replace("^XB", "");
                    }
                    list.Add(printStr);
                }

                File.WriteAllText($"PrintContent_{DateTime.Now.ToString("yyyy_MM_dd_HH_mm_ss")}.print", string.Join(" ", list));

                return true;
            }


            var sucess = false;
            try
            {
                var client = new System.Net.Sockets.TcpClient();
                client.Connect(url.Split(':')[0], Convert.ToInt32(url.Split(':')[1]));

                foreach (string str in strArray)
                {
                    var printStr = str;
                    if (isSinglePrint)
                    {
                        printStr = str.Replace("^XB", "");
                    }
                    client.Client.Send(System.Text.Encoding.ASCII.GetBytes(printStr));
                }
                client.Close();

                sucess = true;
            }
            catch (Exception err) { }

            return sucess;
        }
        public static bool PrintByMqtt(string OpName,string LeftTop,string RightTop,string LeftBottom,string BarCode)
        {
            var sucess = false;
            try
            {
                string topic = ConfigurationManager.AppSettings["MqttUrl"].Split(',')[1];
                string templeName = ConfigurationManager.AppSettings["PrintTempleName"];
                string opName = "OPPrint";
                string sendMsg = $"{opName}~1~ZT411{OpName}~{templeName}{OpName}|BarCode^Code0^{BarCode}|TEXT^TEXT1^{RightTop}|TEXT^TEXT0^{LeftTop}|TEXT^TEXT2^{LeftBottom}|TEXT^TEXT3^{BarCode}";
                Task.Run(() => Mqtt.Publish(topic, sendMsg));
            }
            catch(Exception err)
            {
                sucess = false;
            }
            return sucess;
        }
    }
}
