using System;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using NPrinterCLib;
using System.Runtime.InteropServices;
using NiiPrinterCLib;

namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
	{
        NClassLib nei;
        DisplayInfoDelegate objDelegate;
        NClassLib.NCALLBACK method;
        private delegate void DisplayInfoDelegate(string Text);
        private ulong max;
        private ulong current;

        [DllImport("gdi32.dll", ExactSpelling = true, SetLastError = true)]
        static extern IntPtr CreateCompatibleDC(IntPtr hdc);

        public Form1()
        {
            InitializeComponent();
            nei = new NClassLib();
            objDelegate = new DisplayInfoDelegate(DisplayResults);
            method = new NClassLib.NCALLBACK(showResult);

            cmbBarcodeID.SelectedIndex = 0;
            cmbHRI.SelectedIndex = 0;
            cmbSpin.SelectedIndex = 0;

        }

        private void btnNStartDoc_Click(object sender, EventArgs e)
        {
            int ret = 0;
            int jid = 0;

            ret = nei.NStartDoc(txtPrtName.Text, out jid);
            if(ret < 0)
            {
                MessageBox.Show("Error");
            }

            Text5.Text = Convert.ToString(jid);

            txtResult.Text = ret.ToString();
        }

        private void btnNEndDoc_Click(object sender, EventArgs e)
        {
            int ret = 0;

            ret = nei.NEndDoc(txtPrtName.Text);
            if(ret < 0)
            {
                MessageBox.Show("Error");
            }

            txtResult.Text = ret.ToString();
        }

        private void btnNPrint_Click(object sender, EventArgs e)
        {
            int ret = 0;
            int jid = 0;

            ret = nei.NPrint(txtPrtName.Text, Encoding.ASCII.GetBytes(txtNPrintData.Text), (uint)txtNPrintData.Text.Length, out jid);
            if(ret < 0)
            {
                MessageBox.Show("Error");
            }

            Text5.Text = Convert.ToString(jid);

            txtResult.Text = ret.ToString();
        }

        private void btnNImagePrint_Click(object sender, EventArgs e)
        {
            int ret = 0;
            int jid = 0;
            byte prtType;
            IntPtr hdc;

            switch(comboBox2.Text)
            {
            case "0x00":
                prtType = 0x00;
                break;
            case "0x01":
                prtType = 0x01;
                break;
            case "0x02":
                prtType = 0x02;
                break;
            case "0x10":
                prtType = 0x10;
                break;
            default:
                return;
            }

            // Get Device context(HDC)
            Graphics g = Picture1.CreateGraphics();
            g.DrawImage(Picture1.Image, 0, 0, Picture1.Image.Width, Picture1.Image.Height);
            hdc = g.GetHdc();

            // Output Image
            ret = nei.NImagePrint(txtPrtName.Text, hdc, Picture1.Image.Width, Picture1.Image.Height, prtType, out jid);
            if(ret < 0)
            {
                MessageBox.Show("Error");
            }

            Text5.Text = Convert.ToString(jid);

            // Open Resource
            g.ReleaseHdc(hdc);
            g.Dispose();

            txtResult.Text = ret.ToString();
        }

        private void btnNGetStatus_Click(object sender, EventArgs e)
        {
            int ret = 0;
            long st = 0;

            ret = nei.NGetStatus(txtPrtName.Text, out st);
            txtStatus.Text = Convert.ToString(st);

            txtResult.Text = ret.ToString();
        }

        // NGetInfomation<Model ID=2>
        private void cmdGetModel_Click(object sender, EventArgs e)
        {
            int ret = 0;
            long tm = 0;
            byte[] dat = new byte[64];

            ret = nei.NGetInformation(txtPrtName.Text, (byte)2, dat, out tm);
            if(ret < 0)
            {
                MessageBox.Show("Error");
            }

            // Model&Time
            Text4.Text = "";
            for(int i = 0; i < 64; i++)
            {
                Text4.Text += (char)dat[i];
            }
            Text3.Text = Convert.ToString(tm);
        }

		private void cmdSample_Click(object sender, EventArgs e)
		{
            int i = 0;
			int ret = 0;
			int cmd = 0;
            int jid = 0;
            int sjid = 0;
            string wk;
			IntPtr hdc;

			byte[] dat = new byte[64];
			long tm = 0;
			long stm = 0;
			long etm = 0;
			long id = 0;
			long st = 0;
			bool flg;

			// デバイスコンテキスト(HDC)取得
			Graphics g = Picture1.CreateGraphics();
			g.DrawImage(Picture1.Image, 0, 0, Picture1.Image.Width, Picture1.Image.Height);
			hdc = g.GetHdc();

			for(i = 1; i <= int.Parse(textBox1.Text); i++)
			{
				Application.DoEvents();

				ret = nei.NStartDoc(txtPrtName.Text, out jid);
				if(ret < 0)
				{
					MessageBox.Show("Error");
				}

				Text5.Text = Convert.ToString(jid);

				// 印字開始宣言
				cmd = int.Parse(Text5.Text);
				wk = "1D\"G\"11" + cmd.ToString("X2") + "000000";
				ret = nei.NPrint(txtPrtName.Text, Encoding.ASCII.GetBytes(wk), (uint)wk.Length, out sjid);
				if(ret < 0)
				{
					MessageBox.Show("Error");
				}

				// 印字前処理
				wk = "1B\"@\"1B4AFF1D7E801B6101";
				ret = nei.NPrint(txtPrtName.Text, Encoding.ASCII.GetBytes(wk), (uint)wk.Length, out sjid);
				if(ret < 0)
				{
					MessageBox.Show("Error");
				}

				// ドキュメントイメージ出力
				wk = "\"TEST Image START\"0a";
				ret = nei.NPrint(txtPrtName.Text, Encoding.ASCII.GetBytes(wk), (uint)wk.Length, out sjid);
				if(ret < 0)
				{
					MessageBox.Show("Error");
				}
				ret = nei.NImagePrint(txtPrtName.Text, hdc, Picture1.Image.Width, Picture1.Image.Height, 1, out sjid);
				if(ret < 0)
				{
					MessageBox.Show("Error");
				}
				wk = "1B\"@TEST Image END\"0a";
				ret = nei.NPrint(txtPrtName.Text, Encoding.ASCII.GetBytes(wk), (uint)wk.Length, out sjid);
				if(ret < 0)
				{
					MessageBox.Show("Error");
				}

				// 印字後処理
				wk = "1B4A78";
				ret = nei.NPrint(txtPrtName.Text, Encoding.ASCII.GetBytes(wk), (uint)wk.Length, out sjid);
				if(ret < 0)
				{
					MessageBox.Show("Error");
				}
				wk = "1D\"G\"10";
				ret = nei.NPrint(txtPrtName.Text, Encoding.ASCII.GetBytes(wk), (uint)wk.Length, out sjid);
				if(ret < 0)
				{
					MessageBox.Show("Error");
				}

                ret = nei.NEndDoc(txtPrtName.Text);
				if(ret < 0)
				{
					MessageBox.Show("Error");
				}

				// 印字完了待ちLoop
				stm = (long)System.Environment.TickCount;
				flg = true;
				while(true)
				{
					Application.DoEvents();

					// Job ID取得
					ret = nei.NGetInformation(txtPrtName.Text, (byte)19, dat, out tm);
					if(ret < 0)
					{
						MessageBox.Show("NGetInformation Error" + Convert.ToString(ret));
						flg = false;
						break;
					}

                    id = (long)dat[0];
					if (jid == id)
					{
						break;
					}

					// 3秒以上経過
					etm = (long)System.Environment.TickCount;
					if ((etm - stm) > 3000)
					{
						// Status
						ret = nei.NGetStatus(txtPrtName.Text, out st);
						if(ret < 0)
						{
							MessageBox.Show("NGetStatus Error");
						}

						txtStatus.Text = Convert.ToString(st);

						if((st & 0x7F) > 0)
						{
							wk = "1D\"G\"10";
							ret = nei.NPrint(txtPrtName.Text, Encoding.ASCII.GetBytes(wk), (uint)wk.Length, out sjid);
							if(ret < 0)
							{
								MessageBox.Show("NPrint Error");
							}
						}

                        MessageBox.Show("3秒以上経過");
						flg = false;
						break;
					}
				}

				// Error
				if(flg == false)
				{
					break;
				}

				textBox2.Text = Convert.ToString(i);
			}

			// リソース開放
			g.ReleaseHdc(hdc);
			g.Dispose();
		}

		private void btnNEnumPrinters_Click(object sender, EventArgs e)
		{
            int ret = 0;
			int size = 0;
			long wk = 0;
			StringBuilder printerNames;

            ret = nei.NEnumPrinters(null, out wk);
            if(ret == 0)
            {
                size = (int)wk;
                printerNames = new StringBuilder(size);
                ret = nei.NEnumPrinters(printerNames, out wk);

                txtPrtName.Text = printerNames.ToString();
            }

            txtResult.Text = ret.ToString();
        }

        private void cmdStatusMode_Click(object sender, EventArgs e)
		{
			timer1.Enabled = !timer1.Enabled;
		}

		private void timer1_Tick(object sender, EventArgs e)
		{
			btnNGetStatus_Click(sender, e);
		}

		private void btnNGetPrinterFromID_Click(object sender, EventArgs e)
		{
            int ret = 0;
            StringBuilder printerNames = new StringBuilder(100);

			ret = nei.NGetPrinterFromID(textBox3.Text, printerNames);
            if(ret == 0)
            {
                txtPrtName.Text = printerNames.ToString();
            }

            txtResult.Text = ret.ToString();
        }

        private void btnNDeletePrinter_Click(object sender, EventArgs e)
		{
            int ret = nei.NDeletePrinter(txtPrtName.Text);

            txtResult.Text = ret.ToString();
        }

        private void btnNRenamePrinter_Click(object sender, EventArgs e)
		{
            int ret = nei.NRenamePrinter(txtPrtName.Text, textBox4.Text);

            txtResult.Text = ret.ToString();
        }

        private void btnNGetPrinterInf_Click(object sender, EventArgs e)
		{
            int ret = 0;
            int size = 0;
			long wk = 0;
			StringBuilder PrinterInf;

			if(nei.NGetPrinterInf(txtPrtName.Text, null, out wk) != 0)
            {
                return;
            }

            size = (int)wk;
			PrinterInf = new StringBuilder(size);

            ret = nei.NGetPrinterInf(txtPrtName.Text, PrinterInf, out wk);
            if(ret == 0)
            {
                textBox5.Text = PrinterInf.ToString();
            }

            txtResult.Text = ret.ToString();
        }

        private void btnNOpenPrinter_Click(object sender, EventArgs e)
		{
            int ret = 0;

//          ret = nei.NOpenPrinter(txtPrtName.Text, byte.Parse(textBox6.Text), method);  // for Ver.3.0.0.0 or later
//          ret = nei.NOpenPrinter(txtPrtName.Text, byte.Parse(textBox6.Text), null);    // for Ver.3.0.0.0 or later
            ret = nei.NOpenPrinter(txtPrtName.Text, byte.Parse(textBox6.Text));          // for Ver.3.2.0.0 or later

//          ret = nei.NOpenPrinter(txtPrtName.Text, byte.Parse(textBox6.Text));          // for Ver.1.0.8.0 or earlier

            txtResult.Text = ret.ToString();
        }

        private void btnNClosePrinter_Click(object sender, EventArgs e)
		{
            int ret = nei.NClosePrinter(txtPrtName.Text);

            txtResult.Text = ret.ToString();
        }

        private void btnNImagePrintF_Click(object sender, EventArgs e)
		{
            int ret = 0;
            int jid = 0;

            if(nei.NImagePrintF(txtPrtName.Text, textBox7.Text, 0x01, out jid) == 0)
            {
                ret = nei.NPrint(txtPrtName.Text, Encoding.ASCII.GetBytes("0a0a0a1b69"), 10, out jid);
            }

            txtResult.Text = ret.ToString();
        }

        private void btnNResetPrinter_Click(object sender, EventArgs e)
		{
            int ret = nei.NResetPrinter(txtPrtName.Text);

            txtResult.Text = ret.ToString();
        }

        private void btnNEnumDoc_Click(object sender, EventArgs e)
		{
            int size = 0;
			StringBuilder DocList;

			size = nei.NEnumDoc(txtPrtName.Text, null);
            if(size >= 0)
            {
                DocList = new StringBuilder(size);
                size = nei.NEnumDoc(txtPrtName.Text, DocList);

                textBox8.Text = DocList.ToString();
            }

            txtResult.Text = size.ToString();
        }

        private void btnNDeleteDoc_Click(object sender, EventArgs e)
		{
            int ret = 0;
            int value = int.Parse(textBox9.Text);

            ret = nei.NDeleteDoc(txtPrtName.Text, value);

            txtResult.Text = ret.ToString();
        }

        private void btnNinitializeNetwork_Click(object sender, EventArgs e)
        {
            int ret = 0;

            if(cmbNInitialize.Text == "ON")
            {
                ret = nei.NInitializeNetwork(1);
            }
            else
            {
                ret = nei.NInitializeNetwork(0);
            }

            txtResult.Text = ret.ToString();
        }

        private void btnNScanPrinters_Click(object sender, EventArgs e)
		{
            int ret = nei.NScanPrinters(3000);

            txtResult.Text = ret.ToString();
        }

        private void btnNBlockSendSetting_Click(object sender, EventArgs e)
		{
            int ret = 0;
            Byte type = Byte.Parse(comboBox1.Text);

			ret = nei.NBlockSendSetting(txtPrtName.Text, type);

            txtResult.Text = ret.ToString();
        }

        private void DisplayResults(string Text)
        {
            listBox1.Items.Add(Text);
            listBox1.SelectedIndex = listBox1.Items.Count - 1;
        }

		private void showResult(string i_prt, int i_type, int i_value1, int i_value2)
		{
            this.Invoke(objDelegate, i_prt + ": i_type:" + i_type + " Result[" + i_value1 + ", " + i_value2 +"]");
		}

		private void btnNBufferClear_Click(object sender, EventArgs e)
		{
            int ret = nei.NBufferClear(txtPrtName.Text);

            txtResult.Text = ret.ToString();
        }

        private void btnNTCPPortLock_Click(object sender, EventArgs e)
		{
            int ret = 0;
			Byte value = Byte.Parse(comboBox3.Text);

			ret = nei.NTCPPortLock(txtPrtName.Text, value);

            txtResult.Text = ret.ToString();
        }

        private void btnNSetCallback_Click(object sender, EventArgs e)
        {
            if(cmbCallback.Text == "ON")
            {
                nei.NSetCallback(method);
            }
            else
            {
                nei.NSetCallback(null);
            }
        }

        private void cmdCallbackClear_Click(object sender, EventArgs e)
        {
            listBox1.Items.Clear();
        }

        private void btnNBarcode_Click(object sender, EventArgs e)
        {
            int nmsRet = 0;
            int nmsLen;
            int nmsJobID;
            int jid = 0;
            uint nmsX;
            uint nmsY;
            uint nmsWidth;
            uint nmsHeight;
            byte nmuType;
            IntPtr hdc;
            Graphics g;

            // XとY
            if((txtNBarcodeX.Text.Equals(string.Empty)) || (txtNBarcodeY.Text.Equals(string.Empty)))
            {
                return;
            }

            nmsX = uint.Parse(txtNBarcodeX.Text);
            nmsY = uint.Parse(txtNBarcodeY.Text);

            // 幅と高さ
            if((txtNBarcodeWidth.Equals(string.Empty)) || (txtNBarcodeHeight.Equals(string.Empty)))
            {
                return;
            }

            nmsWidth = uint.Parse(txtNBarcodeWidth.Text);
            nmsHeight = uint.Parse(txtNBarcodeHeight.Text);

            // データ長
            nmsLen = txtNBarcodeData.Text.Length;

            // 印字モード
            switch(cmbNBarcodeMode.Text)
            {
            case "0x00":
                nmuType = 0x00;
                break;
            case "0x01":
                nmuType = 0x01;
                break;
            case "0x02":
                nmuType = 0x02;
                break;
            case "0x10":
                nmuType = 0x10;
                break;
            default:
                return;
            }

            // Get Device context(HDC)
            g = barcodeImage.CreateGraphics();

            // Create solid brush.
            SolidBrush whiteBrush = new SolidBrush(Color.White);

            // Create rectangle.
            Rectangle rect = new Rectangle(0, 0, (int)nmsWidth, (int)nmsHeight);
            g.FillRectangle(Brushes.White, rect);

            hdc = g.GetHdc();
            
            //nmsRet = nei.NImagePrint(txtPrtName.Text, hdc, Picture1.Image.Width, Picture1.Image.Height, nmuType, out jid);

            // 実行
            nmsRet = nei.NBarcode2(hdc, nmsX, nmsY, out nmsWidth, out nmsHeight, Encoding.ASCII.GetBytes(txtNBarcodeData.Text), nmsLen);
            

            txtResult.Text = nmsRet.ToString();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            //int retry = 0;
            //int type = 0;
            //long ob = 0;
            //string fpath = "D:\\01_資料\\02_開発\\画像\\dog01.bmp";
            //string printerName = "PRT002";
            //var ret = 0;

            //for(retry = 0; retry < 200; retry++)
            //{
            //    NIIClassLib PrintDev = new NIIClassLib();
            //    ret = PrintDev.NiiImagePrintF(printerName, fpath, 255, out ob);
            //    if(ret != 0)
            //    {
            //        type = 1;
            //        continue;
            //    }
            //    string i_dat = "1B4A4F" + "1B6D" + "1D4730";
            //    ret = PrintDev.NiiPrint(printerName, i_dat, i_dat.Length, out ob);
            //    if(ret != 0)
            //    {
            //        type = 2;
            //        continue;
            //    }
            //    break;
            //}

            //listBox1.Items.Add("type:" + type.ToString() + " result:" + ret.ToString() + " retry:" + retry.ToString());
            //listBox1.SelectedIndex = listBox1.Items.Count - 1;
        }

        private void btnContinuous_Click(object sender, EventArgs e)
        {
            if(btnContinuous.Text == "Continuous")
            {
                if(ulong.TryParse(txtMax.Text, out max) == false)
                {
                    return;
                }

                timer2.Enabled = true;
                btnContinuous.Text = "Printing...";
            }
            else
            {
                timer2.Enabled = false;
                btnContinuous.Text = "Suspended";
            }
        }

        private void timer2_Tick(object sender, EventArgs e)
        {
            int i;
            int id = 0;
            string data = string.Empty;

            current++;

            data = "\"count:" + current.ToString() + "\"0A";

            for (i = 0; i < 15; i++)
            {
                data += "\"HHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHH\"0A";
            }

            data += "0A0A0A0A0A1B6D";

            nei.NPrint(txtPrtName.Text, Encoding.ASCII.GetBytes(data), (uint)data.Length, out id);

            if ((max != 0) && (current >= max))
            {
                timer2.Enabled = false;
                btnContinuous.Text = "Continuous";
            }
        }

        private void txtNBarcodeData_TextChanged(object sender, EventArgs e)
        {

        }

        private void btnNBarcodeSettings_Click(object sender, EventArgs e)
        {
            int nmsRet = 0;
            uint nmsWidth;
            uint nmsHeight;
            char Option1;
            char Option2;
            char Option3;
            char Option4;
            uint nmsBarcodeID;
            uint nmsHRI;
            uint nmsSpin;
            

            if ((txtWidth.Text.Equals(string.Empty)) || (txtHeight.Text.Equals(string.Empty)) || (txtOption1.Text.Equals(string.Empty)) || (txtOption2.Text.Equals(string.Empty)) || (txtOption3.Text.Equals(string.Empty)) || (txtOption4.Text.Equals(string.Empty)))
            {
                return;
            }

            nmsWidth = uint.Parse(txtWidth.Text);
            nmsHeight = uint.Parse(txtHeight.Text);
            Option1 = (char)int.Parse(txtOption1.Text);
            Option2 = (char)int.Parse(txtOption2.Text);
            Option3 = (char)int.Parse(txtOption3.Text);
            Option4 = (char)int.Parse(txtOption4.Text);
            nmsBarcodeID = (uint)cmbBarcodeID.SelectedIndex;
            if (cmbBarcodeID.SelectedIndex >= 23)
            {
                nmsBarcodeID += 7;
            }
            nmsHRI = (uint)cmbHRI.SelectedIndex;
            nmsSpin = (uint)cmbSpin.SelectedIndex;

            nmsRet = nei.NBarcodeSettings(nmsBarcodeID,nmsWidth,nmsHeight,Option1,Option2,Option3,Option4,nmsHRI,nmsSpin,0);
            txtResult.Text = nmsRet.ToString();

        }
    }
}
