using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Runtime.InteropServices;
using System.IO.Ports;

using HPRT.Printer;
using System.Text.RegularExpressions;


namespace PrtWinDemo
{
    public partial class PrtWinDemoForm : Form
    {
        //支持页模式的机型
        public List<string> PageModePrinterList = new List<string> { "TP806", "TP805", "TP801", "MLP2", "HM-E200", "PT562" };

        HPRTPrinter printer = null;
        bool isPageModePrinter;
        string imagePath;
        int Index;

        public PrtWinDemoForm()
        {
            InitializeComponent();
            setButtonEnable(false);

            this.cmbPortType.SelectedIndex = 1;
            this.cmbModel.Text = "HM-E200";
            this.cmbModel.Focus();
            this.txtPortSetting.Text = "USB";
            this.cmbImage.SelectedIndex = 0;
        }
        private void setButtonEnable(bool isEnable)
        {
            btnConnect.Enabled = !isEnable;
            btnStop.Enabled = isEnable;
            this.grbBtn.Enabled = isEnable;
            
        }
        private void btnClose_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void btnConnect_Click(object sender, EventArgs e)
        {
            string modelsetting = this.cmbModel.Text;
            string portsetting = this.txtPortSetting.Text;
            int result = 0;

            if (null == printer)
            {
                if (null == (printer = new HPRTPrinter(modelsetting)))
                {
                    MessageBox.Show("Creator Model Failed!");
                    return;
                }
            }
            else 
            {
                printer.Model = modelsetting;
            }
            if (Constants.E_SUCCESS == (result = printer.PortOpen(portsetting)))
            {
                //设置字符集
                //printer.SetCharacterSet(Constants.CHARACTERSET_DEFAULT);

                this.tboxInfo.Text = "Connect Succeed";
                setButtonEnable(true);
                //判断是否支持页模式
                isPageModePrinter = PageModePrinterList.Contains(modelsetting);
                if (!isPageModePrinter)
                {
                    this.btnPrintLabel.Enabled = false;
                }
            }
            else
                MessageBox.Show("Port Failed!");
        }
        private void btnStop_Click(object sender, EventArgs e)
        {
            this.tboxInfo.Text = "Close Port";
            printer.PortClose();
            setButtonEnable(false);
        }

        private void btnPrintLabel_Click(object sender, EventArgs e)  //TP开头的 垂直移动单元 为：0.0625 ，其他 垂直移动单元为：0.125 //在页模式下 对齐无效。
        {
            double hMotion = 0.125, vMotion = 0.125;    // distance per dot
            int pageWidth =50, pageHeight = 50;        // mm
            int width_dots = (int)(pageWidth / hMotion);
            int height_dots = (int)(pageHeight / vMotion);
            int result = 0;
  
            if (CheckPrinterState())
            {
                printer.Initialize();
                printer.SelectPageMode();

                printer.SetPageModePrintArea(0, 0, width_dots, height_dots);
                 
                result = printer.SetPageModePrintDirection(Constants.PRINT_DIRECTION_LEFT_TO_RIGHT);

                result = printer.SetPageModeHorizontalPosition(20);
                result = printer.SetPageModeVerticalPosition(8);
                 //printer.PrintText("123", Constants.ALIGNMENT_CENTER, Constants.TEXT_FONT_DW_MODE, Constants.TEXT_SIZE_0WIDTH | Constants.TEXT_SIZE_0HEIGHT);

                 printer.PrintTwoQRCode("123", 5, 1, 1, "456", 5, 2, 2);

               
                ////print TEXT DOUBLE
                //result = printer.SetPageModePrintDirection(Constants.PRINT_DIRECTION_LEFT_TO_RIGHT);
                //result = printer.SetPageModeHorizontalPosition(120);
                //result = printer.SetPageModeVerticalPosition(8);
                //printer.PrintText("TEXT TWO", Constants.ALIGNMENT_LEFT, Constants.TEXT_FONT_EMPHASIZED, Constants.TEXT_SIZE_2WIDTH | Constants.TEXT_SIZE_2HEIGHT);
                
               
                ////print EAN128
                //result = printer.SetPageModePrintDirection(Constants.PRINT_DIRECTION_LEFT_TO_RIGHT);
                //result = printer.SetPageModeHorizontalPosition(20);
                //result = printer.SetPageModeVerticalPosition(96);
                //result = printer.PrintBarCode(Constants.BARCODE_CODE128, "{A1101123456789", 1, 60, Constants.ALIGNMENT_CENTER, Constants.BARCODE_HRI_BELOW);

                ////print EAN13
                //result = printer.SetPageModePrintDirection(Constants.PRINT_DIRECTION_LEFT_TO_RIGHT);
                //result = printer.SetPageModeHorizontalPosition(20);
                //result = printer.SetPageModeVerticalPosition(194);
                //result = printer.PrintBarCode(Constants.BARCODE_EAN13, "2501138000002", 2, 60, Constants.ALIGNMENT_CENTER, Constants.BARCODE_HRI_BELOW);
                
                ////print QRCode
                //result = printer.SetPageModePrintDirection(Constants.PRINT_DIRECTION_LEFT_TO_RIGHT);
                //result = printer.SetPageModeHorizontalPosition(80);
                //result = printer.SetPageModeVerticalPosition(80);
                //result = printer.PrintBarCode(Constants.SYMBOL_QRCODE1, "QRCODE 1 123456", 5, 60, Constants.ALIGNMENT_LEFT, Constants.BARCODE_HRI_NONE);

                ////print QRCode
                //result = printer.SetPageModePrintDirection(Constants.PRINT_DIRECTION_LEFT_TO_RIGHT);
                //result = printer.SetPageModeHorizontalPosition(140);
                //result = printer.SetPageModeVerticalPosition(328);
                //result = printer.PrintBarCode(Constants.SYMBOL_QRCODE1, "QRCODE 2 654321", 5, 60, Constants.ALIGNMENT_LEFT, Constants.BARCODE_HRI_NONE);
                
                ////print PDF417  
                //result = printer.SetPageModePrintDirection(Constants.PRINT_DIRECTION_LEFT_TO_RIGHT);
                //result = printer.SetPageModeHorizontalPosition(20);
                //result = printer.SetPageModeVerticalPosition(440);
                //result = printer.PrintSymbol(Constants.SYMBOL_STANDARD_PDF417, "China 0123456 ABC +_*&", Constants.PDF417_ERROR_CORRECTION_LEVEL_0, 3, 2, Constants.ALIGNMENT_LEFT);
                ////UPCA
                //result = printer.SetPageModePrintDirection(Constants.PRINT_DIRECTION_LEFT_TO_RIGHT);
                //result = printer.SetPageModeHorizontalPosition(20);
                //result = printer.SetPageModeVerticalPosition(504);
                //result = printer.PrintBarCode(Constants.BARCODE_UPC_A, "023150456784", 2, 60, Constants.ALIGNMENT_LEFT, Constants.BARCODE_HRI_BELOW);
                ////UPCE
                //result = printer.SetPageModePrintDirection(Constants.PRINT_DIRECTION_LEFT_TO_RIGHT);
                //result = printer.SetPageModeHorizontalPosition(20);
                //result = printer.SetPageModeVerticalPosition(592);
                //result = printer.PrintBarCode(Constants.BARCODE_UPC_E, "01220000899", 2, 60, Constants.ALIGNMENT_LEFT, Constants.BARCODE_HRI_BELOW);

                ////print EAN8
                //result = printer.SetPageModePrintDirection(Constants.PRINT_DIRECTION_LEFT_TO_RIGHT);
                //result = printer.SetPageModeHorizontalPosition(20);
                //result = printer.SetPageModeVerticalPosition(680);
                //result = printer.PrintBarCode(Constants.BARCODE_EAN8, "1542656", 2, 60, Constants.ALIGNMENT_CENTER, Constants.BARCODE_HRI_BELOW);
                
                ////print CODE39
                //result = printer.SetPageModePrintDirection(Constants.PRINT_DIRECTION_LEFT_TO_RIGHT);
                //result = printer.SetPageModeHorizontalPosition(0);
                //result = printer.SetPageModeVerticalPosition(100);
                //result = printer.PrintBarCode(Constants.BARCODE_CODE39, "*10401YY000002009*", 2, 100, Constants.ALIGNMENT_CENTER, Constants.BARCODE_HRI_BELOW);
                
                ////print  ITF
                //result = printer.SetPageModePrintDirection(Constants.PRINT_DIRECTION_LEFT_TO_RIGHT);
                //result = printer.SetPageModeHorizontalPosition(20);
                //result = printer.SetPageModeVerticalPosition(856);
                //result = printer.PrintBarCode(Constants.BARCODE_ITF, "11231111032125", 2, 60, Constants.ALIGNMENT_CENTER, Constants.BARCODE_HRI_BELOW);
                ////print  BARCODE
                //result = printer.SetPageModePrintDirection(Constants.PRINT_DIRECTION_LEFT_TO_RIGHT);
                //result = printer.SetPageModeHorizontalPosition(20);
                //result = printer.SetPageModeVerticalPosition(944);
                //result = printer.PrintBarCode(Constants.BARCODE_CODABAR, "A40156A", 2, 60, Constants.ALIGNMENT_CENTER, Constants.BARCODE_HRI_BELOW);
                ////print  CODE93
                //result = printer.SetPageModePrintDirection(Constants.PRINT_DIRECTION_LEFT_TO_RIGHT);
                //result = printer.SetPageModeHorizontalPosition(20);
                //result = printer.SetPageModeVerticalPosition(1032);
                //result = printer.PrintBarCode(Constants.BARCODE_CODE93, "CODE930093", 2, 60, Constants.ALIGNMENT_CENTER, Constants.BARCODE_HRI_BELOW);
                
                printer.PrintAndReturnStandardMode();
                printer.CancelPrintData();  
                //printer.PositionNextLabel(); 

            }
        }

        private void btnDirectIO_Click(object sender, EventArgs e)
        {
            byte[] writedata = new byte[] { 0x1D, 0x72, 0x01 };
            //byte[] writedata = new byte[] { 0x1B, 0x74, 0x15 };
            int readnum = 0;
            byte[] readdata = new byte[1];
            printer.DirectIO(writedata, readdata, readdata.Length, ref readnum);
            if (readnum > 0)
            {
                tboxInfo.Text = "";
                for (int i = 0; i < readnum; i++)
                {
                    tboxInfo.Text += Convert.ToString(readdata[i], 16) + " ";
                }
            }
        }

        private void btnState_Click(object sender, EventArgs e)
        {
            uint printer_state = 0;
            printer.CheckPrinterState(ref printer_state);
            if (Constants.STS_NORMAL == printer_state)
            {
                MessageBox.Show("Printer state normal.");
            }
            else
            {
                CheckPrinterState();
            }
        }

        private void btnPrintReceipt_Click(object sender, EventArgs e)
        {
            if (CheckPrinterState())
            {

               // printer.Initialize();
               
               // printer.PrintText("چاپگر\n", Constants.ALIGNMENT_CENTER, Constants.TEXT_FONT_UNDERLINE_MODE, Constants.TEXT_SIZE_0WIDTH | Constants.TEXT_SIZE_0HEIGHT);
               
                //printer.PrintText("Receipt:270500027                Cashier:01012\n", Constants.ALIGNMENT_LEFT, Constants.TEXT_NORMAL_MODE, Constants.TEXT_SIZE_0WIDTH | Constants.TEXT_SIZE_0HEIGHT);
                //printer.PrintText("----------------------------------------------\n", Constants.ALIGNMENT_LEFT, Constants.TEXT_NORMAL_MODE, Constants.TEXT_SIZE_0WIDTH | Constants.TEXT_SIZE_0HEIGHT);
                //printer.PrintText("  Commodity Code         Price        Quantity\n", Constants.ALIGNMENT_LEFT, Constants.TEXT_FONT_EMPHASIZED | Constants.TEXT_FONT_UNDERLINE_MODE, Constants.TEXT_SIZE_0WIDTH | Constants.TEXT_SIZE_0HEIGHT);
                //printer.PrintText("01.9940228004700          3.98           1.181\n", Constants.ALIGNMENT_LEFT, Constants.TEXT_NORMAL_MODE, Constants.TEXT_SIZE_0WIDTH | Constants.TEXT_SIZE_0HEIGHT);
                //printer.PrintText("   banana                       subtotal:4.70 \n", Constants.ALIGNMENT_LEFT, Constants.TEXT_NORMAL_MODE, Constants.TEXT_SIZE_0WIDTH | Constants.TEXT_SIZE_0HEIGHT);
                //printer.PrintText("02.996100800220           6.00           0.376\n", Constants.ALIGNMENT_LEFT, Constants.TEXT_NORMAL_MODE, Constants.TEXT_SIZE_0WIDTH | Constants.TEXT_SIZE_0HEIGHT);
                //printer.PrintText("   noodle                       subtotal:2.20 \n", Constants.ALIGNMENT_LEFT, Constants.TEXT_NORMAL_MODE, Constants.TEXT_SIZE_0WIDTH | Constants.TEXT_SIZE_0HEIGHT);
                //printer.PrintText("03.6921644701204          3.50           1    \n", Constants.ALIGNMENT_LEFT, Constants.TEXT_NORMAL_MODE, Constants.TEXT_SIZE_0WIDTH | Constants.TEXT_SIZE_0HEIGHT);
                //printer.PrintText("   fruit juice                  subtotal:3.50 \n", Constants.ALIGNMENT_LEFT, Constants.TEXT_NORMAL_MODE, Constants.TEXT_SIZE_0WIDTH | Constants.TEXT_SIZE_0HEIGHT);
                //printer.PrintText("04.9940316000602          5.16           0.116\n", Constants.ALIGNMENT_LEFT, Constants.TEXT_NORMAL_MODE, Constants.TEXT_SIZE_0WIDTH | Constants.TEXT_SIZE_0HEIGHT);
                //printer.PrintText("   flour                        subtotal:0.60 \n", Constants.ALIGNMENT_LEFT, Constants.TEXT_NORMAL_MODE, Constants.TEXT_SIZE_0WIDTH | Constants.TEXT_SIZE_0HEIGHT);
                //printer.PrintText("----------------------------------------------\n", Constants.ALIGNMENT_LEFT, Constants.TEXT_NORMAL_MODE, Constants.TEXT_SIZE_0WIDTH | Constants.TEXT_SIZE_0HEIGHT);
                //printer.PrintText("Total:                  RMB             11.00 \n", Constants.ALIGNMENT_LEFT, Constants.TEXT_NORMAL_MODE, Constants.TEXT_SIZE_0WIDTH | Constants.TEXT_SIZE_0HEIGHT);
                //printer.PrintText("Payment:                RMB            101.00 \n", Constants.ALIGNMENT_LEFT, Constants.TEXT_NORMAL_MODE, Constants.TEXT_SIZE_0WIDTH | Constants.TEXT_SIZE_0HEIGHT);
                //printer.PrintText("Change:                 RMB             90.00 \n", Constants.ALIGNMENT_LEFT, Constants.TEXT_NORMAL_MODE, Constants.TEXT_SIZE_0WIDTH | Constants.TEXT_SIZE_0HEIGHT);
                //printer.PrintText("Sold Quantity:                           4    \n", Constants.ALIGNMENT_LEFT, Constants.TEXT_NORMAL_MODE, Constants.TEXT_SIZE_0WIDTH | Constants.TEXT_SIZE_0HEIGHT);
                //printer.PrintText("  13th,Sep,2014   16:50:19\n", Constants.ALIGNMENT_CENTER, Constants.TEXT_NORMAL_MODE, Constants.TEXT_SIZE_0WIDTH | Constants.TEXT_SIZE_0HEIGHT);
                //printer.PrintTwoQRCode("banana,noodle,fruit juice,flour.Total:RMB 11.00", 3, Constants.ALIGNMENT_LEFT, Constants.ALIGNMENT_CENTER, "NO:270500027", 2, Constants.ALIGNMENT_CENTER, 42);
                //printer.PrintText("Thank you for patronizing\n", Constants.ALIGNMENT_CENTER, Constants.TEXT_FONT_UNDERLINE_MODE, Constants.TEXT_SIZE_0WIDTH | Constants.TEXT_SIZE_0HEIGHT);
                //printer.PrintText("PRT-Mart\n", Constants.ALIGNMENT_CENTER, Constants.TEXT_FONT_REVERSE, Constants.TEXT_SIZE_1WIDTH | Constants.TEXT_SIZE_0HEIGHT);
            //    //printer.CutPaper(Constants.FULL_CUT, 120);

            }
        }

        private bool CheckPrinterState()
        {
            PrinterState printerState = new PrinterState();
            printer.GetState(ref printerState);
            tboxInfo.Text = "";

            if (printerState.PAPEREMPTY == true)
            {
                MessageBox.Show("Printer paper not present,please insert the printing paper.");
                return false;
            }
            if (printerState.COVEROPEN == true)
            {
                MessageBox.Show("Printer paper cover open,please check paper cover.");
                return false;
            }
            if (printerState.PAPERNEAREND == true)
            {
                tboxInfo.Text = "Printer paper near end,please insert the printing paper.";
            }
            if (printerState.MSR_READY == true)
            {
                //to do
            }
            if (printerState.SMARTCARD_READY == true)
            {
                //to do
            }
            if (printerState.ERROR == true)
            {
                MessageBox.Show("Printer state error.");
                return false;
            }
            if (printerState.NOT_OPEN == true)
            {
                MessageBox.Show("Printer not open.");
                return false;
            }
            if (printerState.OFFLINE == true)
            {
                MessageBox.Show("Printer offline,please check printer state.");
                return false;
            }

            return true;
        }

        private void cmbPortType_SelectedIndexChanged(object sender, EventArgs e)
        {
            string porttype = this.cmbPortType.Text.ToUpper();
            if ("COM" == porttype)
                this.txtPortSetting.Text = "COM3,BAUDRATE_115200";
            else if ("NET" == porttype)
                this.txtPortSetting.Text = "Net,192.168.1.37";
            else if ("USB" == porttype)
            {
                this.txtPortSetting.Text = "USB";
            }
            else if ("LPT" == porttype)
                this.txtPortSetting.Text = "LPT1";
            else
            {
                this.txtPortSetting.Text = "Invalid";
            }
        }

        private void btnWinFont_Click(object sender, EventArgs e)
        {
            if (CheckPrinterState())
            {
                string imgepath = Application.StartupPath + @"\sample.bmp";
                //中文
                printer.PrintText2Image(imgepath, "打印测试", FontStyle.Regular, 25);
                //阿拉伯语
                printer.PrintText2Image(imgepath, " اختبار الطباعة ", FontStyle.Underline, 25);
                //泰语
                printer.PrintText2Image(imgepath, "กรุณาเปิดดูวิดีโอใ", FontStyle.Bold, 25);
                //韩语
                printer.PrintText2Image(imgepath, "프린터 시험", FontStyle.Strikeout, 40);
            }
        }

        private void btnVersion_Click(object sender, EventArgs e)
        {
            int[] Version = new int[3];

            if (HPRT.Printer.Constants.E_SUCCESS == printer.GetPrinterVersion(Version))
                MessageBox.Show("Printer FirmwareVersion:"
                    + Version[0].ToString() +"."
                    + Version[1].ToString() + "."
                    + Version[2].ToString()
                    );
        }

        private void btnDownLoadImage_Click(object sender, EventArgs e)
        {
            if (CheckPrinterState())
            {
                int result=0;
                OpenFileDialog dlg = new OpenFileDialog();
                dlg.Filter = "Image files|*.bmp;*.gif;*.jpg;*.png;";
                string imgMethod = this.cmbImage.Text;

                if (dlg.ShowDialog() == DialogResult.OK)
                {
                    string fname = dlg.FileName;
                    if ("Image" == imgMethod)
                    {
                        imagePath = fname;
                    }
                    else if ("BufferedImage" == imgMethod)
                    {
                        result = printer.DefineBufferedImage(fname);
                    }
                    else if ("NVImage" == imgMethod)
                    {
                        result = printer.DefineNVImage(fname, (byte)'1', (byte)'1');
                    }
                    else if ("NVImageCompatible" == imgMethod)
                    {
                        result = printer.DefineNVImageCompatible(new string[] { fname }, 1);
                    }
                    else if ("DownloadImage" == imgMethod)
                    {
                        result = printer.DefineDownloadedImage(fname, (byte)'1', (byte)'0');
                    }
                    else if ("DownloadedImageCompatible" == imgMethod)
                    {
                        result = printer.DefineDownloadedImageCompatible(fname);
                    }

                    Index = this.cmbImage.SelectedIndex;
                    if (Constants.E_SUCCESS == result)
                    {
                        MessageBox.Show("DownLoad Succeed.");
                        btnPrint.Enabled = true;
                    }
                    else
                    {
                        MessageBox.Show("DownLoad Failed." + result.ToString());
                        btnPrint.Enabled = false;
                    }
                }
            }
        }

        private void btnPrint_Click(object sender, EventArgs e)
        {
            switch (Index)
            {
                case 0: printer.PrintImage(imagePath, 0);
                        btnPrint.Enabled = false;
                        break;
                case 1: printer.PrintBufferedImage();
                        btnPrint.Enabled = false;
                        break;
                case 2: printer.PrintNVImage((byte)'1', (byte)'1'); break;
                case 3: printer.PrintNVImageCompatible(1, 0); break;
                case 4: printer.PrintDownloadedImageCompatible(0); break;
                default:
                    break;
            }
        }

    }
}

