using System;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Net.Mail;
using System.Xml;
using System.Xml.Linq;
using McMaster.Extensions.CommandLineUtils;

namespace XmlToHtml
{
    public class XMLController
    {
        //Server options
        [Option(ShortName = "InputXml")]
        public string InputXml { get; }

        [Option(ShortName = "OutputHtml")]
        public string OutputHtml { get; }

        [Option(ShortName = "FileVersion")]
        public string FileVersion { get; }

        [Option(ShortName = "ServerPath")]
        public string ServerPath { get; }

        //Result dir

        [Option(ShortName = "ResultDir")]
        public string ResultDir { get; }

        //LocalOptions
        [Option(ShortName = "LocalPath")]
        public string LocalPath { get; }
   
        //Xml result load for changes

        [Option(ShortName = "PathToHtmlResultLocal")]
        public string PathToHtmlResultLocal { get; }

        //Mail Part

        [Option(ShortName = "MailPath")]
        public string MailPath { get; }

        [Option(ShortName = "MailFrom")]
        public string MailFrom { get; }

        [Option(ShortName = "Password")]
        public string Password { get; }

        public void OnExecute()
        {
            XmlTransformer.Transform(InputXml, OutputHtml);
            HtmlReplace.Replace(OutputHtml);


            
            string Report;

        
                string path = LocalPath;
                string source_dir = ResultDir;
                var foldertime = new DirectoryInfo(path).GetDirectories("*", SearchOption.TopDirectoryOnly).OrderByDescending(d => d.LastWriteTimeUtc).First();
                string destination_dir = path + foldertime;

                // Create subdirectory structure in destination        
                foreach (string file_name in System.IO.Directory.GetFiles(source_dir, "*", System.IO.SearchOption.AllDirectories))
                {
                    string finalPath = destination_dir + System.IO.Path.Combine(destination_dir, file_name.Substring(source_dir.Length));
                    System.IO.File.Copy(file_name, finalPath);
                }

            XmlDocument xml = new XmlDocument();                   
            xml.Load(InputXml);
            XmlNode node = xml.DocumentElement.SelectSingleNode("/test-run/test-suite");       
            string atr = node.Attributes["result"]?.InnerText;

            //MailPart
            try

            {
                Report = File.ReadAllText(PathToHtmlResultLocal);

                if (string.IsNullOrEmpty(Report))
                {
                    //email part
                    MailMessage mail = new MailMessage();
                    SmtpClient SmtpServer = new SmtpClient(MailPath);

                    mail.From = new MailAddress(MailFrom);
                  
                    mail.To.Add(MailFrom);
                   
                    mail.Subject = "! Devtools Automation Test Report Failed";

                    mail.IsBodyHtml = true;
                    string htmlBody;

                    htmlBody = "<b>No test was correctly started. Please check the test enviroment.</b>";

                    mail.Body = htmlBody;

                    SmtpServer.Port = 587;
                    SmtpServer.EnableSsl = true;
                    SmtpServer.DeliveryMethod = SmtpDeliveryMethod.Network;
                    SmtpServer.Credentials = new System.Net.NetworkCredential(MailFrom, Password);
                    SmtpServer.Send(mail);
                }
                else
                {
                    MailMessage mail = new MailMessage();
                    SmtpClient SmtpServer = new SmtpClient(MailPath);
                    mail.From = new MailAddress(MailFrom);
                   
                    mail.To.Add(MailFrom);
                                         
                    mail.Subject = "Report";
                    mail.IsBodyHtml = true;
                    string htmlBody;
                    htmlBody = (string)Report;


                    mail.Body = htmlBody;
                    SmtpServer.Port = 587;
                    SmtpServer.EnableSsl = true;
                    SmtpServer.DeliveryMethod = SmtpDeliveryMethod.Network;
                    SmtpServer.Credentials = new System.Net.NetworkCredential(MailFrom, Password);
                    SmtpServer.Send(mail);


                }

            }

            catch (Exception ex1)
            {
                Console.WriteLine(ex1.Message);

                MailMessage mail = new MailMessage();
                SmtpClient SmtpServer = new SmtpClient(MailPath);
                

                mail.From = new MailAddress(MailFrom);
            
                mail.To.Add(MailFrom);
                
                mail.Subject = "! Devtools Automation Test Report Failed";

                mail.IsBodyHtml = true;

                string htmlBody;

                htmlBody = "<html><body><b>Unable to retrieve collected TestData. Please check the test enviroment</b><br><br>" + ex1 + "</body></html>";

                mail.Body = htmlBody;

                SmtpServer.Port = 587;
                SmtpServer.EnableSsl = true;
                SmtpServer.DeliveryMethod = SmtpDeliveryMethod.Network;
                SmtpServer.Credentials = new System.Net.NetworkCredential(MailFrom, Password);
                SmtpServer.Send(mail);

            }

        }


    }
}
