using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;

namespace skyscraper5.Skyscraper.Scraper.Storage.InMemory.Model
{
    internal class DsmCcModuleBlacklist
    {
        public DsmCcModuleBlacklist(FileInfo fi)
        {
            entries = new List<Tuple<int, int, int, ushort, byte>>();
            ListPath = fi;
			if (!fi.Exists)
                return;

            StreamReader streamReader = fi.OpenText();
            while (!streamReader.EndOfStream)
            {
                string readLine = streamReader.ReadLine();
                if (string.IsNullOrEmpty(readLine))
                    continue;
                if (string.IsNullOrWhiteSpace(readLine))
                    continue;
                if (readLine.StartsWith("#"))
                    continue;
                string[] strings = readLine.Split(';');
                int networkId = Int32.Parse(strings[0]);
                int transportStreamId = Int32.Parse(strings[1]);
                int elementaryPid = Int32.Parse(strings[2]);
                ushort moduleId = UInt16.Parse(strings[3]);
                byte moduleVersion = Byte.Parse(strings[4]);
                //TODO: consider download progress
                entries.Add(new Tuple<int, int, int, ushort, byte>(networkId, transportStreamId, elementaryPid, moduleId, moduleVersion));
            }
            streamReader.Close();
        }

        public FileInfo ListPath { get; set; }

        private List<Tuple<int, int, int, ushort, byte>> entries;
        public bool IsBlacklisted(int currentNetworkId, int currentTransportStreamId, int elementaryPid, ushort moduleId, byte moduleVersion)
        {
            int count = 0;
            var checkMe = new Tuple<int, int, int, ushort, byte>(currentNetworkId, currentTransportStreamId, elementaryPid, moduleId, moduleVersion);
            foreach(Tuple<int, int, int, ushort, byte> entry in entries)
            {
                if (entry.Equals(checkMe))
                    count++;
            }
            return count >= 3;
        }

        public void AddFailedModule(int cnid, int ctsid, int pid, ushort mid, ushort mVersion, double progress)
        {
            ListPath.Refresh();
            FileStream fileStream = ListPath.Open(ListPath.Exists ? FileMode.Append : FileMode.CreateNew);
            StreamWriter streamWriter = new StreamWriter(fileStream, System.Text.Encoding.UTF8);
            streamWriter.WriteLine(String.Format("{0};{1};{2};{3};{4};{5}", cnid, ctsid, pid, mid, mVersion, progress));
            streamWriter.Flush();
            streamWriter.Close();
            fileStream.Close();
            fileStream.Dispose();
        }
    }
}
