using log4net;
using skyscraper5.Skyscraper.IO;
using skyscraper5.Skyscraper.Net.Pcap;
using skyscraper5.Skyscraper.Plugins;
using skyscraper8.Skyscraper.Scraper.Storage;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace skyscraper8.Skyscraper.Net.Pcap
{
	[SkyscraperPlugin]
	[StorageId(1)]
	[StorageName("PCAP Writer")]
	internal class PcapIpTrafficHandler : IpTrafficHandler
	{
		private static readonly ILog logger = LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Name);
		private PcapWriter[] pcapWriters;
		private DirectoryInfo outputDirectory;


		public void HandlePacket(int pid, byte[] payload)
		{
			if (pcapWriters == null)
			{
				pcapWriters = new PcapWriter[0x1fff];

				PluginManager pluginManager = PluginManager.GetInstance();
				string outDirPath = pluginManager.Ini.ReadValue("pcapwriter", "outdir", null);
				if (!string.IsNullOrEmpty(outDirPath))
				{
					outputDirectory = new DirectoryInfo(outDirPath);
					if (!outputDirectory.Exists)
						outputDirectory.EnsureExists();
				}
			}
			if (pcapWriters[pid] == null)
			{
				string fname = String.Format("{0:X4},{1}.pcap", pid, DateTime.Now.Ticks);
				if (outputDirectory != null)
				{
					fname = Path.Combine(outputDirectory.FullName, fname);
				}
				logger.InfoFormat("Opening file for writing: {0}", fname);
				FileStream fs = File.OpenWrite(fname);
				pcapWriters[pid] = new PcapWriter(fs, TcpdumpNetworkType.RawIp);
			}
			pcapWriters[pid].WritePacket(payload);
		}

		public void Dispose()
		{
			if (pcapWriters != null)
			{
				for (int i = 0; i < pcapWriters.Length; i++)
				{
					if (pcapWriters[i] != null)
						pcapWriters[i].Dispose();
				}
			}
		}
	}
}
