using System;

namespace skyscraper5.Scorcher
{
	internal class TsPacketHeaderBuilder
	{
		public static byte[] BuildHeader(bool pusi, uint pid, int continuityCounter)
		{
			return BuildHeader(false, pusi, false, pid, 0, continuityCounter, null, true);
		}

		public static byte[] BuildHeader(bool tei, bool pusi, bool transportPriority, uint pid, uint tsc, int continuityCounter, byte[] adaptionField = null, bool withPayload = true)
		{
			byte[] buffer = new byte[4 + (adaptionField != null ? adaptionField.Length + 1 : 0)];
			buffer[0] = (byte)'G';

			if (tei)
				buffer[1] |= 0x80;

			if (pusi)
				buffer[1] |= 0x40;

			if (transportPriority)
				buffer[1] |= 0x20;

			if (pid > 0x1fff)
				throw new ArgumentOutOfRangeException(nameof(pid));

			if ((pid & 0x1000) != 0)
				buffer[1] |= 0x10;

			uint pid2 = (pid & 0x0f00) >> 8;
			buffer[1] += (byte)pid2;

			buffer[2] = (byte)(pid & 0x00ff);

			if (tsc > 3)
				throw new ArgumentOutOfRangeException(nameof(tsc));

			tsc <<= 6;
			buffer[3] += (byte)tsc;

			if (adaptionField != null)
			{
				buffer[3] |= 0x20;
				buffer[4] = (byte)adaptionField.Length;
				Array.Copy(adaptionField, 0, buffer, 5, adaptionField.Length);
			}

			if (withPayload)
				buffer[3] |= 0x10;

			continuityCounter &= 0x0000000f;
			buffer[3] += (byte)continuityCounter;
			return buffer;
		}
	}
}
