using System;
using NLog;
using NLog.Config;
using NLog.Targets;
using DataClient;
using System.Net.Sockets;
using System.Net;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Threading.Tasks;
using DataClient.Struct;

namespace Test2
{
	class Program
	{
		static bool cycle = true;
		static void Main(string[] args)
		{
			LogConf();
			//var t = new Task(() => T1());
			//t.Start();
			//T1();
			var str = new STPClient();
			OLD1();
			Console.WriteLine("End acc.");
			Console.ReadKey();
			cycle = false;
			//Console.WriteLine("Hello World!");
		}
		static void LogConf()
		{
			var conf = new LoggingConfiguration();
			var logcon = new ColoredConsoleTarget()
			{
				Name = "logcon",
				Layout = @"${time}|${level:uppercase=true}|${logger}|${message}${when:when=length('${exception}')>0:Inner=|}${exception:format=ToString,StackTrace}"
			};

			conf.AddRule(LogLevel.Trace, LogLevel.Fatal, logcon);
			LogManager.Configuration = conf;
		}

		static void testSocket()
		{
			Socket s = null;
			IPEndPoint ipe = new IPEndPoint(IPAddress.Parse("10.10.45.152"), 1070);
			s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
			var code = "slit history";
			var send = new List<byte>();
			for (var i = 0; i < 4; i++)
				send.Add(0xff);
			send.AddRange(BitConverter.GetBytes((uint)code.Length));
			send.AddRange(Encoding.ASCII.GetBytes(code));
			send.Add(0x00);

			s.Connect(ipe);
			s.Send(send.ToArray());

		}

		static void T1()
		{
			var t = new NETClient("10.10.45.151", 1070);
			t.RetryCount = 10;
			t.RetryInterval = 0.1;
			var work_dir = "D:/techcycle";
			for (var i = 0; i < 49; i++) {
				Console.WriteLine("vdp-" + i.ToString("D2"));
				byte[] a;
				try
				{
					a = t.Full_Download(new DateTime(2021, 06, 07), i, 3);
				}
				catch(Exception e)
				{
					Console.WriteLine("Can't get techcycle.");
					Console.WriteLine(e.Message);
					continue;
				}
				if (a == null || a.Length == 0)
				{
					Console.WriteLine("Empty array.");
					a = Array.Empty<byte>();
				}
				else
				{
					var b = ByteConverter.BytesToTechcycles(a);
					foreach(var c in b)
					{
						Console.Write(c.index.ToString() + "\t");
						Console.WriteLine(c.start.ToString("yyyy.MM.dd HH.mm.ss"));
					}
				}
			}

		}

		static void T2()
		{
			var t = new NETClient("10.10.45.151", 1070);
			t.Connect();
			t.SendBytes(t.CreateCode((uint)NETClient.Code.download, "20210607.003"));
			var a = t.ReceiveBytes();
			if (a == null || a.Length == 0)
			{
				Console.WriteLine("Empty array.");
				a = Array.Empty<byte>();
			}
			for (var j = 0; j < a.Length; j++)
			{
				Console.Write(" " + a[j].ToString("X2"));
				if ((j + 1) % 16 == 0)
					Console.WriteLine();
			}
			t.Close();
		}

		static void OLD6()
		{
			var t = new NETClient("10.10.45.151", 1070);
			t.RetryCount = 10;
			t.RetryInterval = 0.1;
			var work_dir = "D:/pasports";
			Directory.CreateDirectory(work_dir);
			var dir_year = t.Full_Dir_Browse();
			Console.WriteLine("Read main dir.");
			foreach (var a in dir_year)
			{
				if (a == "current") continue;
				Console.WriteLine(" Read dir " + a + ".");
				var dir_month = t.Full_Dir_Browse(a);
				foreach(var b in dir_month)
				{
					Console.WriteLine("  Read dir " + b + ".");
					var dir_day = t.Full_Dir_Browse(b);
					foreach(var c in dir_day)
					{
						Console.WriteLine("   Read dir " + c + ".");
						var pasports = t.Full_Dir_Browse(c);
						foreach(var d in pasports)
						{
							var count = 0;
							Pasport pasp;
							do
							{
								Console.WriteLine("    Read " + count + " pasp: " + d);
								pasp = t.Full_Pasp_Download(d);
								count = (pasp.HasData && pasp.hasPasport) ? 3 : count + 1;
							} while (count < 3);
							Directory.CreateDirectory(work_dir + "/" + c);
							var res = pasp.PaspByte;
							var name = (pasp.hasPasport && !string.IsNullOrEmpty(pasp.nplav)) ? pasp.nplav : (pasp.numVDP.HasValue) ? pasp.numVDP.Value.ToString("D2") : "Jane_Doe";
							Console.Write("     Write pasp " + name + ": byte; ");
							using (var file = new FileStream(work_dir + "/" + c + "/" + name, FileMode.Create, FileAccess.Write))
							{
								file.Write(res, 0, res.Length);
							}
							Console.WriteLine("read;");
							using (var file = new StreamWriter(work_dir + "/" + c + "/" + name + "_read.txt"))
							{
								file.WriteLine(pasp.HasData); file.WriteLine(pasp.numVDP); file.WriteLine(pasp.dStart); file.WriteLine(pasp.dEnd);
								file.WriteLine(pasp.hasPasport); file.WriteLine(pasp.kod_npl); file.WriteLine(pasp.nplav); file.WriteLine(pasp.rm);
								file.WriteLine(pasp.splav); file.WriteLine(pasp.iS); file.WriteLine(pasp.notd); file.WriteLine(pasp.vessl);
								file.WriteLine(pasp.diam); file.WriteLine(pasp.prpl); file.WriteLine(pasp.tin); file.WriteLine(pasp.dzap);
								file.WriteLine(pasp.dlog); file.WriteLine(pasp.last); file.WriteLine(pasp.dlper); file.WriteLine(pasp.nazn);
								file.WriteLine(pasp.kompl); file.WriteLine(pasp.izl); file.WriteLine(pasp.robm); file.WriteLine(pasp.rizol);
								file.WriteLine(pasp.dkr); file.WriteLine(pasp.nkon); file.WriteLine(pasp.pos); file.WriteLine(pasp.ukaz);
								file.WriteLine(pasp.zakaz); file.WriteLine(pasp.kat); file.WriteLine(pasp.pril); file.WriteLine(pasp.rezerved);
							}
						}
					}
				}
			}
		}
		static void OLD5()
		{
			var t = new NETClient("10.10.45.151", 1070);
			while (cycle)
			{
				var arr = t.Full_Server_Time();
				Console.WriteLine(arr.ToString("yyyy.MM.dd HH.mm.ss"));
				Task.Delay(1000).Wait();
			}
		}
		static void OLD4()
		{
			var t = new NETClient("10.10.45.151", 1070);
			var task1 = new Task(() => t.Full_Download(new DateTime(2021, 06, 04), 33, 1));
			var task2 = new Task(() => t.Full_Download(new DateTime(2021, 06, 04), 34, 1));
			task1.Start();
			task1.GetAwaiter().GetResult();
			task2.Start();
			task2.GetAwaiter().GetResult();
		}
		static void OLD3()
		{
			var rnd = new Random();
			var t = new NETClient("10.10.45.151", 1070);
			string[] a = null;
			int c = 0;
			for (var i = 0; i < 8; i++)
			{
				if (a == null || a.Length == 0)
					a = t.Full_Dir_Browse();
				else
					a = t.Full_Dir_Browse(a[c]);
				Console.WriteLine((i + 1).ToString() + " test:");
				if (a != null)
					foreach (var e in a) Console.WriteLine(e);
				else
					Console.WriteLine("NULL");
				c = (a == null) ? 0 : rnd.Next(0, a.Length);
			}
		}
		static void OLD2()
		{
			string[] tes = {
				"version",
			"file list",
			"download",
			"pasp browse",
			"pasp download",
			"pasp find",
			"prog list",
			"prog download",
			"server time",
			"download usov",
			"slit history",
			"keep alive",
			"vdp cycle",
			"vdp active",
			"vdp last cycle",
			"rmt watchdog",
			"set rmt watchdog",
			"print job",
			"pasp find2",
			"pasp browse2",
			"arch history",
			"download nh",
			"download usov nhv",
			"dir browse",
			"vdp sim med",
			"vdp flags",
			"user flags",
			"user motd",
			"user mail",
			"download tvso",
			"pasp download tvso",
			"pasp find tvso",
			"pasp browse tvsov",
			"korpus cycle",
			"korpus last cycle",
			"download fdan",
			"client version",
			"measure id",
			"read vdp config",
			"write vdp config",
			"read tvso config",
			"delete vdp config",
			"get plav personal",
			"get server info",
			"ctrl split",
			"ctrl set time",
			"ctrl end tc",
			"ctrl remove",
			"ctrl spool",
			"save pasport",
			"save pasport 90",
			"find time bugs",
			"update pasport",
			"get pasp by id",
			"cp com find pasp by temp",
			"get splav list",
			"get field val list",
			"get plav list form",
			"get pasp by priv",
			"print job 2",
			"get pasp by name",
			"get pasp by id 90",
			"find pasp by temp 90",
			"get pasp by priv 90",
			"get pasp by name 90",
			"get plav list form 90",
			"ctrl split db",
			"ctrl set time db",
			"ctrl remove db",
			"update stat",
			"get cur params arr",
			"get cur params",
			"get cur params arr 5",
			"get cur params 5",
			"fix db cycle",
			"by name",
			"test"
			};
			var t = new NETClient("10.10.45.151", 1070);
			using (var file = new StreamWriter(Directory.GetCurrentDirectory() + "/test_by_name.txt"))
			{
				for (var i = 0; i < tes.Length; i++)
				{
					var res = t.Full_By_Name(tes[i]);
					if (res != null)
						foreach (var b in res)
							file.Write("0x" + b.ToString("X2") + " ");
					file.Write("- ");
					if (res != null)
						file.Write(BitConverter.ToUInt32(res).ToString("D4") + " - ");
					file.WriteLine(tes[i]);
				}
			}
		}
		static void OLD1()
		{
			var t = new NETClient("10.10.45.151", 1070);
			var task = new Task<byte[]>(() => t.Full_Download_NH(new DateTime(2021, 06, 27), 12, 4));
			task.Start();
			do
			{
				Console.WriteLine("Status: " + (Math.Round(t.Status * 10000) / 100).ToString() + "%");
				Task.Delay(1000).Wait();
			} while (task.Status == TaskStatus.Running);
			var res = (task.IsCompletedSuccessfully) ?
				task.GetAwaiter().GetResult() :
				Array.Empty<byte>();
			using (var file = new FileStream(Directory.GetCurrentDirectory() + "/test1.txt", FileMode.Create, FileAccess.Write))
			{
				file.Write(res, 0, res.Length);
			}
		}



	}
}
