using System;
using System.IO;

namespace skyscraper5.Skyscraper.Net.Pcap
{
    internal class PcapWriter : IDisposable
    {
        public DateTime StartTime { get; private set; }
        public TcpdumpNetworkType NetworkType { get; }
        private readonly Stream outputStream;
        private readonly BinaryWriter binaryWriter;
        private bool disposed;

        public PcapWriter(Stream outputStream, TcpdumpNetworkType networkType)
        {
            NetworkType = networkType;
            this.outputStream = outputStream;
            binaryWriter = new BinaryWriter(outputStream);
            binaryWriter.Write(0xa1b2c3d4);
            binaryWriter.Write((ushort)2);
            binaryWriter.Write((ushort)4);
            binaryWriter.Write(0);
            binaryWriter.Write((uint)0);
            binaryWriter.Write((uint)65536);
            binaryWriter.Write((uint)networkType);
            StartTime = DateTime.Now;
        }

        public void Dispose()
        {
            if (disposed)
                return;

            disposed = true;
            binaryWriter.Flush();
            outputStream.Flush();
            outputStream.Close();
            outputStream.Dispose();
        }

        public void WritePacket(byte[] buffer)
        {
            if (disposed)
                return;

            TimeSpan span = DateTime.Now - StartTime;
            binaryWriter.Write((uint)span.TotalSeconds);
            binaryWriter.Write((uint)(span.Milliseconds * 1000));
            binaryWriter.Write((uint)buffer.Length);
            binaryWriter.Write((uint)buffer.Length);
            binaryWriter.Write(buffer);
        }
    }
}
