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

namespace ZionRobot.Tasks
{
    class JobManager : ZionFoundation.Threading.Thread
    {
        private Models.Process.Workflow workflow;
        private Tasks.Input TInput;
        private Tasks.Extractor TExtractor;
        private Tasks.Output TOutput;
        private Tasks.Synchronizer TSynchronizer;
        //private string sync = "Demo";
        //private string sync = "Publications";
        //private string sync = "Lawsuits";
        private string sync = "Activities";
        //private string sync = "Local";

        internal Models.Process.Workflow Workflow { get => workflow; set => workflow = value; }

        public JobManager(Models.Process.Workflow workflow, bool execute = true)
        {
            this.workflow = workflow;
            this.interval = 1000 * 60 * 1;
            TInput = new Tasks.Input();
            TExtractor = new Tasks.Extractor();
            TOutput = new Tasks.Output();
            TSynchronizer = new Tasks.Synchronizer();

            this.workflow.Folders.Add(new Models.Items.Folder(Persistence.Basic.SearchResultFolder));
            this.Initilize(execute);

            this.workflow.Queue.Start();
        }

        public override void Execute()
        {



            if (!tasksIsAlive())
            {

                if(sync == "Local")
                {
                    string rootPath = @"C:\Temp\html\";
                    Models.Source.Origin source = workflow.SyncConfigurations[0];

                    System.IO.Directory.GetFiles(rootPath + @"andamentos", @"*.json").ToList().ForEach(file =>
                    {
                        string fileName = System.IO.Path.GetFileName(file);
                        TSynchronizer.SyncFromLocal(source, file, "Andamentos");

                        while (TSynchronizer.Running)
                        {
                            System.Threading.Thread.Sleep(2000);
                        }

                        System.IO.File.Move(file, rootPath + @"sincronizados\andamentos\" + fileName);
                    });

                    /*System.IO.Directory.GetFiles(rootPath + @"garantias", @"*.json").ToList().ForEach(file =>
                    {
                        string fileName = System.IO.Path.GetFileName(file);
                        TSynchronizer.SyncFromLocal(source, file, "Depositos");

                        while (TSynchronizer.Running)
                        {
                            System.Threading.Thread.Sleep(2000);
                        }

                        System.IO.File.Move(file, rootPath + @"sincronizados\garantias\" + fileName);
                    });

                    System.IO.Directory.GetFiles(rootPath + @"pedidos", @"*.json").ToList().ForEach(file =>
                    {
                        string fileName = System.IO.Path.GetFileName(file);
                        TSynchronizer.SyncFromLocal(source, file, "Pedidos");

                        while (TSynchronizer.Running)
                        {
                            System.Threading.Thread.Sleep(2000);
                        }

                        System.IO.File.Move(file, rootPath + @"sincronizados\pedidos\" + fileName);
                    });

                    System.IO.Directory.GetFiles(rootPath + @"processos", @"*.json").ToList().ForEach(file =>
                    {
                        string fileName = System.IO.Path.GetFileName(file);
                        TSynchronizer.SyncFromLocal(source, file, "Processos");

                        while (TSynchronizer.Running)
                        {
                            System.Threading.Thread.Sleep(2000);
                        }

                        System.IO.File.Move(file, rootPath + @"sincronizados\processos\" + fileName);
                    });*/
                }

                if(sync == "Demo")
                {
                    workflow.OutputConfigurations.ForEach(source =>
                    {
                        TOutput.Execute(source);

                        while (TOutput.Running)
                        {
                            System.Threading.Thread.Sleep(2000);
                        }
                    });

                }

                if(sync == "Publications")
                {
                    workflow.InputConfigurations.ForEach(source =>
                    {
                        TInput.Execute(source);
                        while (TInput.Running)
                        {
                            System.Threading.Thread.Sleep(2000);
                        }
                    });

                    List<Models.Items.File> filesExtraction = workflow.Queues.Extraction;
                    if(filesExtraction.Count > 0)
                    {
                        filesExtraction.ForEach(file =>
                        {
                            TExtractor.Execute(file, workflow.Blueprints);
                        });
                        filesExtraction.Clear();
                    }

                    //List<Models.Items.File> filesIntegration = workflow.Queues.Integration;

                    List<Models.Items.File> filesIntegration = new List<Models.Items.File>();
                    //List<Models.Items.File> filesGrouped = new List<Models.Items.File>();

                    foreach (Models.Items.File file in workflow.Queues.Integration)
                    {
                        if (string.IsNullOrEmpty(file.LawsuitNumber))
                        {
                            filesIntegration.Add(file);
                            continue;
                        }

                        Models.Items.File fi = filesIntegration.Where(f => f.LawsuitNumber == file.LawsuitNumber).FirstOrDefault();

                        if (fi != null)
                        {
                            fi.METAObject.Pages.ForEach(page =>
                            {
                                page.SearchElements.ToList().ForEach(element =>
                                {
                                    if (element.Name == @"ConteudoCompleto")
                                    {
                                        element.Value = string.Format("{0}<hr>{1}", element.Value, file.PublicationContent);
                                    }
                                });
                            });

                            fi.METAObject.Save(fi.META, false, false);

                            file.METAObject.Status = @"GROUPED";
                            file.METAObject.Save(file.META, false, false);
                            file.Status = Persistence.Basic.INTEGRATED;
                            //filesGrouped.Add(file);

                        }
                        else
                        {
                            filesIntegration.Add(file); 
                        }
                    };



                    //var x = (from file in workflow.Queues.Integration
                    //         where file.LawsuitNumber == @"1001023-25.2019.5.02.0613"
                    //         select file).ToList();
                    //});


                    if (filesIntegration.Count > 0)
                    {
                        workflow.OutputConfigurations.ForEach(source =>
                        {

                            filesIntegration.ForEach(file =>
                            {
                                TOutput.Execute(source, file);

                                while (TOutput.Running)
                                {
                                    System.Threading.Thread.Sleep(2000);
                                }
                            });
                        });
                    }
                }

                if (sync == "Lawsuits")
                {
                    List<Models.ZFlow.Lawsuit> lawsuitsToSync = new WebService.Lawsuit().LawsuitsToSync();

                    if (lawsuitsToSync.Count > 0)
                    {
                        workflow.SyncConfigurations.ForEach(source =>
                        {
                            int i = 1;
                            //var x = lawsuitsToSync.Where(l => l.SyncAction == @"Create").ToList();
                            lawsuitsToSync.ForEach(lawsuit =>
                            {
                                TSynchronizer.Execute(source, lawsuit);

                                while (TSynchronizer.Running)
                                {
                                    System.Threading.Thread.Sleep(2000);
                                }
                                i++;
                            });
                        });
                    }

                    /*List<Models.ZFlow.LawsuitPhase> lawsuitPhasesToSync = new WebService.LawsuitPhase().LawsuitPhasesToSync();

                    if (lawsuitPhasesToSync.Count > 0)
                    {
                        workflow.SyncConfigurations.ForEach(source =>
                        {
                            var x = lawsuitPhasesToSync.Where(l => l.SyncAction == @"Create").ToList();
                            x.ForEach(lawsuitPhase =>
                            {
                                if (lawsuitPhase.SyncAction == @"Create")
                                {
                                    TSynchronizer.Execute(source, lawsuitPhase);

                                    while (TSynchronizer.Running)
                                    {
                                        System.Threading.Thread.Sleep(2000);
                                    }
                                }
                            });
                        });
                    }

                    List<Models.ZFlow.LawsuitPhaseProgress> lawsuitPhaseProgressToSync = new WebService.LawsuitPhaseProgress().LawsuitPhaseProgressToSync();

                    if (lawsuitPhaseProgressToSync.Count > 0)
                    {
                        workflow.SyncConfigurations.ForEach(source =>
                        {
                            var x = lawsuitPhaseProgressToSync.Where(l => l.SyncAction == @"Create").ToList();
                            x.ForEach(lawsuitPhaseProgress =>
                            {
                                if (lawsuitPhaseProgress.SyncAction == @"Create")
                                {
                                    TSynchronizer.Execute(source, lawsuitPhaseProgress);

                                    while (TSynchronizer.Running)
                                    {
                                        System.Threading.Thread.Sleep(2000);
                                    }
                                }
                            });
                        });
                    }

                    List<Models.ZFlow.LawsuitDemand> lawsuitDemandsToSync = new WebService.LawsuitDemand().LawsuitDemandsToSync();

                    if (lawsuitDemandsToSync.Count > 0)
                    {
                        workflow.SyncConfigurations.ForEach(source =>
                        {
                            var x = lawsuitDemandsToSync.Where(l => l.SyncAction == @"Create").ToList();
                            x.ForEach(lawsuitDemand =>
                            {
                                if (lawsuitDemand.SyncAction == @"Create")
                                {
                                    TSynchronizer.Execute(source, lawsuitDemand);

                                    while (TSynchronizer.Running)
                                    {
                                        System.Threading.Thread.Sleep(2000);
                                    }
                                }
                            });
                        });
                    }*/
                }


                if (sync == "Activities")
                {
                    List<Models.ZFlow.Activity> activitiesToSync = new WebService.Activity().ActivityToSync();
                    int a = 1;
                    if (activitiesToSync.Count > 0)
                    {
                        workflow.SyncConfigurations.ForEach(source =>
                        {
                            activitiesToSync.ForEach(activity =>
                            {

                                TSynchronizer.Execute(source, activity);

                                while (TSynchronizer.Running)
                                {
                                    System.Threading.Thread.Sleep(2000);
                                }
                                a++;
                            });
                        });
                    }
                }



                /*List<Models.ZFlow.Activity> activitiesToCreateDataJuri = new WebService.Activity().ActivitiesToCreateDataJuri();

                if (activitiesToCreateDataJuri.Count > 0)
                {
                    workflow.SyncConfigurations.ForEach(source =>
                    {
                        activitiesToCreateDataJuri.ForEach(activity =>
                        {
                            TSynchronizer.Execute(source, activity, @"CREATEDATAJURI");

                            while (TSynchronizer.Running)
                            {
                                System.Threading.Thread.Sleep(2000);
                            }
                        });
                    });
                }

                List<Models.ZFlow.Activity> activitiesToCanceling = new WebService.Activity().ActivityToCanceling();

                if (activitiesToCanceling.Count > 0)
                {
                    workflow.SyncConfigurations.ForEach(source =>
                    {
                        activitiesToCanceling.ForEach(activity =>
                        {
                            TSynchronizer.Execute(source, activity, @"CANCELING");

                            while (TSynchronizer.Running)
                            {
                                System.Threading.Thread.Sleep(2000);
                            }
                        });
                    });
                }*/
            }
        }

        private bool tasksIsAlive()
        {
            return TInput.Running || TExtractor.Running || TOutput.Running || TSynchronizer.Running ;
        }


    }
}
