using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection.PortableExecutable;
using System.Text;
using System.Threading.Tasks;
using skyscraper5.DNS.Protocol.ResourceRecords;

namespace skyscraper5.DNS.Protocol
{
	public class Response
	{
		public static Response FromArray(byte[] message)
		{
			Header header = Header.FromArray(message);
			int offset = header.Size;

			if (!header.Response)
			{
				throw new ArgumentException("Invalid response message");
			}

			if (header.Truncated)
			{
				return new Response(header,
					Question.GetAllFromArray(message, offset, header.QuestionCount),
					new List<IResourceRecord>(),
					new List<IResourceRecord>(),
					new List<IResourceRecord>());
			}

			return new Response(header,
				Question.GetAllFromArray(message, offset, header.QuestionCount, out offset),
				ResourceRecordFactory.GetAllFromArray(message, offset, header.AnswerRecordCount, out offset),
				ResourceRecordFactory.GetAllFromArray(message, offset, header.AuthorityRecordCount, out offset),
				ResourceRecordFactory.GetAllFromArray(message, offset, header.AdditionalRecordCount, out offset));
		}

		public Response(Header header, IList<Question> questions, IList<IResourceRecord> answers,
				IList<IResourceRecord> authority, IList<IResourceRecord> additional)
		{
			this.header = header;
			this.questions = questions;
			this.answers = answers;
			this.authority = authority;
			this.additional = additional;
		}

		private Header header;
		private IList<Question> questions;
		private IList<IResourceRecord> answers;
		private IList<IResourceRecord> authority;
		private IList<IResourceRecord> additional;

		public IList<Question> Questions
		{
			get { return questions; }
		}

		public IList<IResourceRecord> AnswerRecords
		{
			get { return answers; }
		}

		public IList<IResourceRecord> AdditionalRecords
		{
			get { return additional; }
		}
	}
}
