using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using DataClients;

namespace Mailing
{
	public class SZOWork
	{
		public TechCycle tc = new TechCycle();
		public DateTime tStart = DateTime.Now;
		public DateTime tEnd = DateTime.Now;
		public TimeSpan workTime
		{
			get
			{
				return tEnd - tStart;
			}
		}
	}

	public static class CollectData
	{
		public static List<SZOWork> GetSZOWorks(DateTime timeStart, DateTime timeEnd, ushort vdp)
		{
			var result = new List<SZOWork>();
			var a = new STPClient();
			int[] chk1 = {
				(int)TechCycle.Operation.cooling_ingot,
				(int)TechCycle.Operation.cooling_reflow,
				(int)TechCycle.Operation.cooling_welding
			};
			int[] chk2 =
			{
				(int)TechCycle.Operation.end_tech_cycle,
				(int)TechCycle.Operation.unloading_loading,
				(int)TechCycle.Operation.looking_welding,
				(int)TechCycle.Operation.unloading_kit
			};

			var tc = a.GetTechCycle(timeStart, timeEnd, vdp);
			var ad = a.GetAnalogDiscret(timeStart, timeEnd, vdp);
			foreach(var cycle in tc)
			{
				if (!chk1.Contains((int)cycle.index) && !chk2.Contains((int)cycle.index))
					continue;
				if (cycle.end < timeStart || cycle.start > timeEnd)
					continue;

				if (cycle.start < timeStart)
					cycle.start = timeStart;
				if (cycle.end > timeEnd)
					cycle.end = timeEnd;

				if (chk1.Contains((int)cycle.index))
				{
					var test =
								(from l in ad.an[13]
								 where l.Item1 >= cycle.start &&
									 l.Item1 <= cycle.end &&
									 l.Item2 >= 30
								 select l).ToArray();
					if (test.Length == 0)
						continue;
				}

				for(var i = 0; i < ad.di[22].Length; i++)
				{
					var ts = ad.di[22][i].Item1;
					var te = (i == (ad.di[22].Length - 1)) ?
						(ad.di[22][i].Item1 < timeEnd) ?
							timeEnd :
							ad.di[22][i].Item1 :
						ad.di[22][i + 1].Item1;

					if (te >= timeStart && ts <= timeStart)
						ts = timeStart;
					if (ts <= timeEnd && te >= timeEnd)
						te = timeEnd;

					var v = ad.di[22][i].Item2;

					if (
							ts <= cycle.end &&
							te >= cycle.start &&
							v.HasValue &&
							v.Value
							)
					{
						var t1 = ts > cycle.start ? ts : cycle.start;
						var t2 = te > cycle.end ? cycle.end : te;
						var res = t2 - t1;
						if (res.TotalMinutes < 15)
							continue;
						result.Add(new SZOWork()
						{
							tc = cycle,
							tStart = t1,
							tEnd = t2
						});
					}
				}
			}
			return result;
		}
				
	}
}
