using Microsoft.VisualBasic;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ZendeskTickets
{
    internal class Program
    {
        private const string TIMESTAMP_FILE = "lastRunTime.txt";
        private const string OUTPUT_SEPERATOR = "========================";
        private const string SINGLE_TAB = "   ";
        static void Main(string[] args)
        {
            FogbugzWrapper.FogbugzClient fogbugzClient;
            if (string.IsNullOrEmpty(Settings1.Default.CurrentToken) && args.Length != 2)
            {
                Console.WriteLine("No Login Credentials!");
                Console.ReadKey();
                return;
            }
            else if(!string.IsNullOrEmpty(Settings1.Default.CurrentToken))
            {
                fogbugzClient = new FogbugzWrapper.FogbugzClient($@"http://{Properties.Settings1.Default.ManuscriptServerAddress}/api.asp?", Settings1.Default.CurrentToken);
            }
            else
            {
                fogbugzClient = new FogbugzWrapper.FogbugzClient($@"http://{Properties.Settings1.Default.ManuscriptServerAddress}/api.asp?", args[0], args[1]);
            }
            if (fogbugzClient == null)
            {
                Console.WriteLine($"Login failed for user:{args[0]}");
                return;
            }
            Settings1.Default.CurrentToken = fogbugzClient.Token;
            Settings1.Default.Save();
            var loggedin = fogbugzClient.IsLoggedIn();
            if (!loggedin) { Console.WriteLine($"ERROR: NOT LOGGED IN"); Console.ReadKey(); return; }
            var zdCaseCount = 0;
            var timeNow = DateTime.Now;
            Console.WriteLine($"{timeNow.ToString()} Searching for ZD cases...");
            int timeDeltaMinutes = 60;            
            if (File.Exists(TIMESTAMP_FILE))
            {
                timeDeltaMinutes = (int)(timeNow - DateTime.Parse(File.ReadAllText(TIMESTAMP_FILE))).TotalMinutes;
            }
            if (Settings1.Default.PublishResultsToZendesk)
            {
                File.WriteAllText(TIMESTAMP_FILE, timeNow.ToString());
            }
            var allZendeskCases = fogbugzClient.GetZendeskCases(timeDeltaMinutes);
            if (allZendeskCases?.FirstOrDefault() == null)
            {
                Console.WriteLine($"ERROR: No Zendesk Cases.");
                return;
            }
            else
            {
                var sb = new StringBuilder();
                foreach (var zendeskCase in allZendeskCases
                    .OrderBy(x=>x.TimeStamp)
                    )
                {
                    var comment = string.IsNullOrEmpty(zendeskCase.LatestEvent.Comment) ? "<no comment>" : $"{zendeskCase.LatestEvent.Comment}";
                    sb.AppendLine($"{Environment.NewLine}{SINGLE_TAB}ZD:{zendeskCase.ZendeskNumber}");
                    var zdfbMapping = "Automatic Update from Manuscript:" +
                        $"\\nMS Case:\\t\\t\\thttp://{Properties.Settings1.Default.ManuscriptServerAddress}/f/cases/{zendeskCase.FogbugzNumber}" +
                        $"\\nEventStatus:\\t\\t\\t{zendeskCase.LatestEvent.StatusString}" +
                        $"\\nTimestamp (PT):\\t\\t\\t{zendeskCase.TimeStamp}" +
                        $"\\nUser:\\t\\t\\t\\t{zendeskCase.LatestEvent.User}" +
                        $"\\nReleaseNote:\\t\\t{zendeskCase.LatestEvent.ReleaseNote}" +
                        $"\\nComment:" +
                        $"\\n{comment}";                        
                    sb.AppendLine(zdfbMapping);
                    var completeUpdate = string.Format("{{\"ticket\": {{\"comment\": {{ \"body\": \"{0}\", \"public\": false}} }} }}", zdfbMapping);
                    sb.AppendLine($"{Environment.NewLine}{OUTPUT_SEPERATOR}");

                    #region curl
                    if (Settings1.Default.PublishResultsToZendesk)
                    {
                        var curl = new System.Diagnostics.Process();
                        curl.StartInfo.FileName = "RunCurl.cmd";

                        var TempFileName = Path.GetTempFileName();
                        using (var sw = new StreamWriter(TempFileName))
                        {
                            sw.WriteLine(completeUpdate);
                        }
                        curl.StartInfo.Arguments = $"{zendeskCase.ZendeskNumber} {TempFileName}";
                        curl.StartInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Minimized;
                        curl.Start();
                        curl.WaitForExit();
                    }
                    
                    #endregion
                    zdCaseCount++;
                }
                if (Settings1.Default.DebugLogging)
                {
                    File.WriteAllText($"ZendeskTickets.{timeNow.ToString("yyMMdd.hhmmss")}.log", sb.ToString());                    
                    Console.Write(sb.ToString());
                }
                Console.WriteLine($"{DateTime.Now.ToString()} Done!" +
                    $"{Environment.NewLine}{SINGLE_TAB}Total Cases: {allZendeskCases.Count}" +
                    $"{Environment.NewLine}{SINGLE_TAB}Updated: {zdCaseCount}" +
                    $"{Environment.NewLine}{OUTPUT_SEPERATOR}" +
                    $"{Environment.NewLine}{OUTPUT_SEPERATOR}");

            }
        }
    }
}
