﻿using System;
using System.IO;
using System.Linq;
using System.Net;
using Trinity.Extensions;
using Trinity.IO;

namespace Trinity.Network.Payloads
{
	internal class NetworkAddressWithTime : ISerializable
	{
		public const ulong NODE_NETWORK = 1;
		public IPEndPoint EndPoint;
		public ulong Services;

		public uint Timestamp;

		public int Size => sizeof(uint) + sizeof(ulong) + 16 + sizeof(ushort);

		void ISerializable.Deserialize(BinaryReader reader)
		{
			Timestamp = reader.ReadUInt32();
			Services = reader.ReadUInt64();
			var address = new IPAddress(reader.ReadBytes(16));
			var port = reader.ReadBytes(2).Reverse().ToArray().ToUInt16(0);
			EndPoint = new IPEndPoint(address, port);
		}

		void ISerializable.Serialize(BinaryWriter writer)
		{
			writer.Write(Timestamp);
			writer.Write(Services);
			writer.Write(EndPoint.Address.MapToIPv6().GetAddressBytes());
			writer.Write(BitConverter.GetBytes((ushort) EndPoint.Port).Reverse().ToArray());
		}

		public static NetworkAddressWithTime Create(IPEndPoint endpoint, ulong services, uint timestamp)
		{
			return new NetworkAddressWithTime
			{
				Timestamp = timestamp,
				Services = services,
				EndPoint = endpoint
			};
		}
	}
}