using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using skyscraper5.Mpeg2;
using skyscraper5.Skyscraper.Scraper;
using skyscraper5.Skyscraper.Scraper.Storage;
using skyscraper8.Skyscraper.Scraper.Storage;

namespace skyscraper5.Skyscraper.RecordingImporter
{
    internal class TsFileCollectionImporter
    {
        public DataStorage DataStorage { get; }
        public ObjectStorage ObjectStorage { get; }
        public DirectoryInfo RootDirectory { get; }

        public TsFileCollectionImporter(DataStorage dataStorage, ObjectStorage objectStorage, DirectoryInfo rootDirectory)
        {
	        DataStorage = dataStorage;
	        ObjectStorage = objectStorage;
            RootDirectory = rootDirectory;
        }

        public void Run()
        {
            Perform(RootDirectory);
        }

        private void Perform(DirectoryInfo di)
        {
            foreach (DirectoryInfo subdirectory in di.GetDirectories())
            {
                Perform(subdirectory);
            }

            foreach (FileInfo fileInfo in di.GetFiles("*.ts"))
            {
                Import(fileInfo);
            }
        }

        private void Import(FileInfo fi)
        {
            if (DataStorage.ImportFileKnown(fi))
                return;

            SkyscraperContext skyscraper = new SkyscraperContext(new TsContext(), DataStorage,ObjectStorage);
            skyscraper.InitalizeFilterChain();
            FileStream fileStream = fi.OpenRead();

            Stopwatch stopwatch = new Stopwatch();
            stopwatch.Start();
            skyscraper.IngestFromStream(fileStream);
            stopwatch.Stop();
            fileStream.Close();

            Console.WriteLine("Took {0} seconds. " + stopwatch.Elapsed.TotalSeconds);
            Console.WriteLine("File was: {0}", fi.Name);

            DataStorage.ImportMarkFileAsKnown(fi, stopwatch.Elapsed, skyscraper.SpecialTsType);
        }
    }
}
