using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ZionRobot.Tasks
{
    class Extractor
    {
        private bool running;
        private ZionExtractor.Analyzer extractor;

        public bool Running { get => this.running; }

        public Extractor()
        {
            this.running = false;
            extractor = new ZionExtractor.Analyzer();
        }

        public void Execute(Models.Items.File file, List<ZionSchematics.Schematics> blueprints)
        {
            running = true;
            int count = 1;
            using (ZionVault.Binder.OCR.Document ocr = new ZionVault.Binder.OCR.Document(file.OCR, false))
            {
                using (ZionVault.Binder.Output.Document metadata = new ZionVault.Binder.Output.Document())
                {
                    int index = 1;

                    ocr.Pages.ForEach(page =>
                    {
                        foreach (ZionSchematics.Schematics bprt in blueprints)
                        {
                            ZionVault.Binder.Output.Page content = extractor.Apply(bprt, page);
                            if (content is null) 
                                continue;
                            metadata.Pages.Add(content);
                            break;
                        }

                        if (metadata.Pages.Where(p => p.Index == page.Index).FirstOrDefault() == null)
                        {
                            ZionVault.Binder.Output.Page data = new ZionVault.Binder.Output.Page
                            {
                                Index = page.Index,
                                Type = @"UNKWON"
                            };
                            metadata.Pages.Add(data);
                        }

                        metadata.Pages.Last().Index = index;

                        index++;

                        count += metadata.Pages.Count();
                    });

                    metadata.Status = Persistence.Basic.INTEGRATION;
                    metadata.Save(file.META, false, false);

                }
            }
            file.Status = Persistence.Basic.INTEGRATION;
            running = false;
        }
    }
}
