using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Text.Json.Serialization;
using System.Threading.Tasks;
using System.Web.Script.Serialization;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace ZionRobot
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            /*//string path = @"C:\Temp\395d068969569bc02d251a843a412491";
            string path = @"C:\Temp\ee3f594c56a67b45b2600a30fefee57a";
            string fileName = System.IO.Path.GetFileName(path);
            string text = System.IO.File.ReadAllText(path);


            JObject a = Newtonsoft.Json.JsonConvert.DeserializeObject<dynamic>(text);
            byte[] bytes = Encoding.UTF8.GetBytes(a["content"].ToString());
            string x = System.Text.Encoding.UTF8.GetString(bytes);

            HtmlAgilityPack.HtmlDocument htmlDoc = new HtmlAgilityPack.HtmlDocument();
            htmlDoc.Load(path);
            //string result = htmlDoc.DocumentNode.SelectSingleNode("//body").InnerHtml;
            string result = htmlDoc.DocumentNode.InnerHtml;

            //byte[] emailContent = System.Text.Encoding.UTF8.GetBytes("{\\rtf1\\ansi\\ansicpg1252\\fromhtml1 \\htmlrtf0 " + result + "}");
            //byte[] emailContent = System.Text.Encoding.UTF8.GetBytes("{\\rtf1\\ansi\\ansicpg1252\\fromhtml1 \\htmlrtf0 " + htmlDoc.DocumentNode.InnerHtml + "}");

            //Independentsoft.Email.Mime.Message mimeMessage = new Independentsoft.Email.Mime.Message(emailContent);

            Independentsoft.Msg.Message msgMessage = new Independentsoft.Msg.Message();
            msgMessage.Encoding = Encoding.UTF8;
            //msgMessage.BodyHtmlText = htmlDoc.DocumentNode.InnerHtml;
            msgMessage.BodyHtmlText = x;
            //msgMessage.BodyHtmlText = result;

            msgMessage.MessageFlags.Add(Independentsoft.Msg.MessageFlag.Read);
            //msgMessage.BodyRtf = emailContent;

            msgMessage.Save($"C:/Temp/{fileName}.msg", true);*/

            // relações dos campos das fases
            /*
            string[] ll = System.IO.File.ReadAllLines(@"C:\Temp\2021.11.08 - Campos DJ.txt");
            string[] i = System.IO.File.ReadAllLines(@"C:\Temp\2021.11.08 - Campos basicos Processos DJ.txt");
            string[] ii = System.IO.File.ReadAllLines(@"C:\Temp\2021.11.08 - Campos especificos Processos DJ.txt");
            string[] x = System.IO.File.ReadAllLines(@"C:\Temp\2021.11.08 - Campos da fase DJ.txt");
            string[] y = System.IO.File.ReadAllLines(@"C:\Temp\2021.11.08 - Campos do Pedido DJ.txt");

            List<string> liness = new List<string>();
            //lines.AddRange(i.ToList());
            //lines.AddRange(ii.ToList());
            //lines.AddRange(ll.ToList());
            liness.AddRange(x.ToList());
            //lines.AddRange(y.ToList());

            foreach (string line in liness)
            {
                string[] value = line.Split(';');

                string fieldOfLaw = null;
                string subgroup = null;
                if(value.Count() > 1)
                {
                    fieldOfLaw = value[1];
                    subgroup = value[2];
                }
                
                
                var a = new ZionVault.WebService.Client(Persistence.WSProperties.UrlApi)._request("PUT",
                $"lawsuit/3/createSoaresDefaultLawsuitPhaseDetail",
                Persistence.WSProperties.Token,
                null,
                new JavaScriptSerializer().Serialize(new
                {
                    entityId = 3,
                    detail = value.First(),
                    fieldOfLaw = fieldOfLaw,
                    subgroup = subgroup
                }),
                null) ;

                if(a.Contains("não encontrado"))
                {
                    Console.WriteLine(a);
                }
            }*/

            /*string[] ll = System.IO.File.ReadAllLines(@"C:\Temp\2021.11.08 - Campos DJ.txt");
            string[] x = System.IO.File.ReadAllLines(@"C:\Temp\2021.11.08 - Campos da fase DJ.txt");
            string[] y = System.IO.File.ReadAllLines(@"C:\Temp\2021.11.08 - Campos do Pedido DJ.txt");

            List<string> lines = new List<string>();
            //lines.AddRange(x.ToList());
            lines.AddRange(y.ToList());

            foreach (string line in lines)
            {
                string content = line.Trim();
                string type = @"TXT";

                if (line.Contains(@"Data"))
                {
                    type = @"DT";
                }

                if (line.Contains(@"Valor"))
                {
                    type = @"CURRENCY";
                }

                var a = new ZionVault.WebService.Client(Persistence.WSProperties.UrlApi)._request("PUT",
                $"lawsuit/3/createEntityDetail",
                Persistence.WSProperties.Token,
                null,
                new JavaScriptSerializer().Serialize(new
                {
                    entityId = 3,
                    name = content,
                    description = content,
                    type = type,
                    createBy = 3,
                    updatBy = 3
                }),
                null);
            }*/

            /*string[] files = System.IO.Directory.GetFiles(@"C:\Users\itsco\Downloads\Reports\Format\Processos", @"*.json");

            foreach (string file in files)
            {
                string text = System.IO.File.ReadAllText(file);

                var a = new ZionVault.WebService.Client(Persistence.WSProperties.UrlApi)._request("PUT",
                   $"importer/3/updateLawsuitEnvolveValue",
                   //$"importer/3/updateDemandFieldsStatus",
                   Persistence.WSProperties.Token,
                   null,
                   text,
                   null);

                if (a == @"Erro")
                {
                    string name = System.IO.Path.GetFileName(file);
                    System.IO.File.Move(file, $"C:\\Users\\itsco\\Downloads\\Reports\\Format\\Processos\\Error\\{name}");
                }

                if (a == @"Sucesso")
                {
                    string name = System.IO.Path.GetFileName(file);
                    System.IO.File.Move(file, $"C:\\Users\\itsco\\Downloads\\Reports\\Format\\Processos\\Sucesso\\{name}");
                }

            }*/

            /* string[] files = System.IO.Directory.GetFiles(@"C:\Users\itsco\Downloads\Reports\Format\Processos", @"*.json");

             foreach (string file in files)
             {
                 string text = System.IO.File.ReadAllText(file);

                 var a = new ZionVault.WebService.Client(Persistence.WSProperties.UrlApi)._request("PUT",
                    $"lawsuit/3/createUpdateLawsuitDemandActivity",
                    //$"importer/3/updateDemandBlob",
                    //$"importer/3/addLawsuitResumoFieldValue",
                    //$"importer/3/updateDemandFieldsStatus",
                    Persistence.WSProperties.Token,
                    null,
                    text,
                    null);

                 if (a == @"Erro")
                 {
                     string name = System.IO.Path.GetFileName(file);
                     System.IO.File.Move(file, $"C:\\Users\\itsco\\Downloads\\Reports\\Format\\Processos\\Error\\{name}");
                 }

                 if (a == @"Sucesso")
                 {
                     string name = System.IO.Path.GetFileName(file);
                     System.IO.File.Move(file, $"C:\\Users\\itsco\\Downloads\\Reports\\Format\\Processos\\Sucesso\\{name}");
                 }

             }*/

            /*string[] files = System.IO.Directory.GetFiles(@"C:\Users\itsco\Downloads\Reports\Format\Processos", @"*.json");

            foreach (string file in files)
            {
                string[] lines = System.IO.File.ReadAllLines(file);

                var a = new ZionVault.WebService.Client(Persistence.WSProperties.UrlApi)._request("PUT",
                   $"importer/3/add",
                   Persistence.WSProperties.Token,
                   null,
                   lines,
                   null);

                if (a == @"Erro")
                {
                    string name = System.IO.Path.GetFileName(file);
                    System.IO.File.Move(file, $"C:\\Users\\itsco\\Downloads\\Reports\\Format\\Processos\\Error\\{name}");
                }

                if (a == @"Sucesso")
                {
                    string name = System.IO.Path.GetFileName(file);
                    System.IO.File.Move(file, $"C:\\Users\\itsco\\Downloads\\Reports\\Format\\Processos\\Sucesso\\{name}");
                }

            }*/

            /*string[] files = System.IO.Directory.GetFiles(@"C:\Temp\EntityDetailsOPT", @"*.txt");

            foreach (string file in files)
            {
                string[] lines = System.IO.File.ReadAllLines(file);
                var a = new ZionVault.WebService.Client(Persistence.WSProperties.UrlApi)._request("PUT",
                   $"lawsuit/3/updateEntityDetailOpt",
                   Persistence.WSProperties.Token,
                   null,
                    new JavaScriptSerializer().Serialize(new
                    {
                        entityId = 3,
                        name = System.IO.Path.GetFileNameWithoutExtension(file),
                        option = lines,
                        createBy = 3,
                        updated = 3
                    }),
                   null);

                if (a == @"Erro")
                {
                    string name = System.IO.Path.GetFileName(file);
                    System.IO.File.Move(file, $"C:\\Temp\\EntityDetailsOPT\\Erro\\{name}");
                }

                if (a == @"Atualizado com sucesso")
                {
                    string name = System.IO.Path.GetFileName(file);
                    System.IO.File.Move(file, $"C:\\Temp\\EntityDetailsOPT\\Sucesso\\{name}");
                }

            }*/

            /*    string file = @"C:\Temp\Soares\2022.03.28 - Redistribuição trabalhista - ZION.txt";
                string[] lines = System.IO.File.ReadAllLines(file);

            lines.ToList().ForEach(line =>
            {
                string[] parts = line.Split(';');
                var a = new ZionVault.WebService.Client(Persistence.WSProperties.UrlApi)._request("PUT",
                  $"lawsuit/3/updateLawsuitAccountable",
                  Persistence.WSProperties.Token,
                  null,
                   new JavaScriptSerializer().Serialize(new
                   {
                       folder_number = parts[0],
                       accountable = parts[1],
                       link = parts[2]
                   }),
                  null); ;

                System.IO.File.AppendAllText(@"C:\Temp\Soares\2022.03.28 - Redistribuição trabalhista - ZION - changeAccountable.txt", line + ";" + a.ToString() + "\n");


            });

            int index = 1;
            int count = 1;
            while(index < 21198)
            {
                string result = new ZionVault.WebService.Client(Persistence.WSProperties.UrlApi)._request("GET",
                    @"exporter/3/getUsers/" + index.ToString(),
                    Persistence.WSProperties.Token,
                    null,
                    string.Empty,
                    null);

                System.IO.File.WriteAllText($"C:\\Projetos\\Soares Picon\\Migração\\Verificar - {count}.json", result);
                index += 1000;
                count++;
            }*/

            /*string result = new ZionVault.WebService.Client(Persistence.WSProperties.UrlApi)._request("GET",
                @"exporter/3/getManualActivities",
                Persistence.WSProperties.Token,
                null,
                string.Empty,
                null);*/

            //int index = 1;
            // 97610


            /*List<string> list1 = System.IO.Directory.GetFiles(@"C:\Projetos\Soares Picon\Migração\Exporta\Activities\Error", "*.json").ToList().Select(item => item.Replace(@"C:\Projetos\Soares Picon\Migração\Exporta\Activities\Error\", "")).ToList();

            list1.ForEach(file =>
            {
                file = file.Replace(@".json", "");
                string result = new ZionVault.WebService.Client(Persistence.WSProperties.UrlApi)._request("GET",
                         @"exporter/3/ActivityInfo/" + file,
                         Persistence.WSProperties.Token,
                         null,
                         string.Empty,
                         null);

                if (result != "Tem pai" && result != "Ignorar" && result[0] != '{')
                {
                    System.IO.File.WriteAllText($"C:\\Projetos\\Soares Picon\\Migração\\Exporta\\Activities\\Error\\Error\\{file}.json", result);
                }

                if (result != "Tem pai" && result != "Ignorar" && result[0] == '{')
                {
                    System.IO.File.WriteAllText($"C:\\Projetos\\Soares Picon\\Migração\\Exporta\\Activities\\Error\\Sucesso\\{file}.json", result);
                }

            });


            List<string> list = new List<string>();
            for(int i = 231082; i <= 248552; i++)
            {
                list.Add(i.ToString());
            }

            Parallel.ForEach( list, new ParallelOptions { MaxDegreeOfParallelism = 3}, (fileId) =>
            {
                string result = new ZionVault.WebService.Client(Persistence.WSProperties.UrlApi)._request("GET",
                       @"exporter/3/ActivityInfo/" + fileId,
                       Persistence.WSProperties.Token,
                       null,
                       string.Empty,
                       null);

                if (result != "Tem pai" && result != "Ignorar" && result[0] != '{')
                {
                    System.IO.File.WriteAllText($"C:\\Projetos\\Soares Picon\\Migração\\Exporta\\Activities\\Error\\{fileId}.json", result);
                }

                if (result != "Tem pai" && result != "Ignorar" && result[0] == '{')
                {
                    System.IO.File.WriteAllText($"C:\\Projetos\\Soares Picon\\Migração\\Exporta\\Activities\\{fileId}.json", result);
                }


            });*/
            /*int index = 1;

            while (index <= 227246) 
            {
                string result = new ZionVault.WebService.Client(Persistence.WSProperties.UrlApi)._request("GET",
                    @"exporter/3/ActivityInfo/" + index.ToString(),
                    Persistence.WSProperties.Token,
                    null,
                    string.Empty,
                    null);

                if(result != "Tem pai" && result != "Ignorar" && result[0] != '{')
                {
                    System.IO.File.WriteAllText($"C:\\Projetos\\Soares Picon\\Migração\\Exporta\\Activities\\Error\\{index}.json", result);
                    index++;
                    continue;
                }

                if (result == "Tem pai" || result == "Ignorar")
                {
                    index++;
                    continue;
                }

                System.IO.File.WriteAllText($"C:\\Projetos\\Soares Picon\\Migração\\Exporta\\Activities\\{index}.json", result);
                index++;

            }*/

            /*List<string> list = System.IO.Directory.GetFiles(@"C:\Projetos\Soares Picon\Migração\Exporta\Activities\Error", "*.json").ToList().Select(item=> item.Replace(@"C:\Projetos\Soares Picon\Migração\Exporta\Activities\Error", "")).ToList();
            List<string> list2 = System.IO.Directory.GetFiles(@"C:\Projetos\Soares Picon\Migração\Exporta\Activities\Error\Sucesso", "*.json").ToList().Select(item => item.Replace(@"C:\Projetos\Soares Picon\Migração\Exporta\Activities\Error\Sucesso", "")).ToList();

            var a = list.Where(file => !list2.Contains(file)).ToList();

            Parallel.ForEach(list,
                new ParallelOptions { MaxDegreeOfParallelism = 2  }, 
                (file) =>
                       {
                           string fileName = System.IO.Path.GetFileName(file);

                            string result = new ZionVault.WebService.Client(Persistence.WSProperties.UrlApi)._request("GET",
                                @"exporter/3/ActivityInfo/" + fileName,
                                Persistence.WSProperties.Token,
                                null,
                                string.Empty,
                                null);

                            if (result != "Tem pai" && result != "Ignorar" && result[0] != '{')
                            {
                                System.IO.File.WriteAllText($"C:\\Projetos\\Soares Picon\\Migração\\Exporta\\Activities\\Error\\Error\\{fileName}", result);
                            }
                            
                           if (result[0] == '{') {
                               System.IO.File.WriteAllText($"C:\\Projetos\\Soares Picon\\Migração\\Exporta\\Activities\\Error\\Sucesso\\{fileName}", result);
                            }

                        
                   });*/


            //System.IO.File.WriteAllText($"C:\\Projetos\\Soares Picon\\Migração\\Verificar - {count}.json", result);



            /*string[] files = System.IO.Directory.GetFiles(@"C:\Projetos\Soares Picon\Migração\json\json\processos", @"*.json");

            foreach (string file in files)
            {
                string[] lines = System.IO.File.ReadAllLines(file);

                string result = new ZionVault.WebService.Client(@"http://zion-legal-flow/")._request("PUT",
                 @"importer/importLawsuits",
                 Persistence.WSProperties.Token,
                 null,
                 lines,
                 null);


                if (result == @"Sucesso")
                {
                    string name = System.IO.Path.GetFileName(file);
                    System.IO.File.Move(file, $"C:\\Projetos\\Soares Picon\\Migração\\json\\json\\exportados\\processos\\sucessos\\{name}");
                } else
                {
                    string name = System.IO.Path.GetFileName(file);
                    System.IO.File.Move(file, $"C:\\Projetos\\Soares Picon\\Migração\\json\\json\\exportados\\processos\\erros\\{name}");
                    System.IO.File.AppendAllText(@"C:\\Projetos\\Soares Picon\\Migração\\json\\json\\exportados\\processos\\erros\\erro.txt", string.Format("{0} - {1}\n===========================================\n\n\n", result, name));

                }
                //System.Threading.Thread.Sleep(500);
            }*/



            InitializeComponent();


            //System.IO.File.AppendAllText(@"C:\\test.txt", $"{method} - {uri}", Encoding.UTF8);

            createBasicDirectories();
            try
            {

                Tasks.JobManager jobManager = new Tasks.JobManager(new Models.Process.Workflow(
                          new Models.Workflow.RoadMap(
                              System.IO.Path.Combine(
                                  Persistence.Basic.ApplicationFolder,
                                  Persistence.Basic.ApplicationName + @".wflow"))), true);
            }
            catch (Exception ex)
            {

                throw;
            }

            /*Tasks.JobManager jobManager = new Tasks.JobManager(new Models.Process.Workflow(
                      new Models.Workflow.RoadMap(
                          System.IO.Path.Combine(@"C:\Temp\Workflow\Demo.wflow"))), true);*/

            this.Visibility = Visibility.Hidden;
            this.ShowInTaskbar = false;
        }

        private void createBasicDirectories()
        {
            System.IO.Directory.CreateDirectory(Persistence.Basic.ApplicationFolder);
            System.IO.Directory.CreateDirectory(Persistence.Basic.BlueprintsFolder);
            System.IO.Directory.CreateDirectory(Persistence.Basic.ConfigurationFolder);
            System.IO.Directory.CreateDirectory(Persistence.Basic.PublicFolder);
            System.IO.Directory.CreateDirectory(Persistence.Basic.DoneFolder);
            System.IO.Directory.CreateDirectory(Persistence.Basic.SearchResultFolder);
            System.IO.Directory.CreateDirectory(Persistence.Basic.LogsFolder);
        }

    }
}
