using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Sophia.Net.DRM
{
	public class SophiaNetEntitlementCollection
	{
		public SophiaNetEntitlementCollection(params Guid[] guids)
		{
			_backend = new Guid[guids.Length];
			Array.Copy(guids,0,_backend,0, guids.Length);
		}

		public SophiaNetEntitlementCollection(byte[] buffer)
		{
			_backend = new Guid[buffer.Length / 16];
			for (int i = 0; i < buffer.Length; i += 16)
			{
				Span<byte> part = new Span<byte>(buffer, i, 16);
				_backend[i / 16] = new Guid(part);
			}
		}

		public byte[] Serialize()
		{
			byte[] outBuffer = new byte[_backend.Length * 16];
			for (int i = 0; i < _backend.Length; i++)
			{
				byte[] iBuffer = _backend[i].ToByteArray();
				Array.Copy(iBuffer, 0, outBuffer, i * 16, 16);
			}

			return outBuffer;
		}

		private Guid[] _backend;

		public bool HasEntitlement(Guid check)
		{
			for (int i = 0; i < _backend.Length; i++)
			{
				if (_backend[i].Equals(check))
					return true;
			}
			return false;
		}

		protected bool Equals(SophiaNetEntitlementCollection that)
		{
			if (this._backend.Length != that._backend.Length)
				return false;

			for (int i = 0; i < this._backend.Length; i++)
			{
				Guid mine = this._backend[i];
				Guid theirs = that._backend[i];
				if (!mine.Equals(theirs))
					return false;
			}

			return true;
		}

		public override bool Equals(object? obj)
		{
			if (ReferenceEquals(null, obj)) 
				return false;
			if (ReferenceEquals(this, obj)) 
				return true;
			if (obj.GetType() != this.GetType()) 
				return false;
			return Equals((SophiaNetEntitlementCollection)obj);
		}

		public override int GetHashCode()
		{
			long result = 0;
			for (int i = 0; i < _backend.Length; i++)
			{
				result += _backend[i].GetHashCode();
			}
			return (int)result;
		}
	}
}
