using System;
using System.Collections.Generic;
using System.IO;
using System.Text.RegularExpressions;

namespace memoQSampleCMSConnector
{
	internal class CMS_Session_Jira
	{
		internal static JiraManager jiraManager = new JiraManager(ConfigurationHelper.Config.jiraApiUrl, ConfigurationHelper.Config.jiraApiUser, ConfigurationHelper.Config.jiraApiPassword);

		private const string xliffFrame = @"<?xml version=""1.0"" encoding=""UTF-8""?><xliff version=""1.2""><file original=""d:\test.txt"" source-language=""!!source!!"" target-language=""!!target!!""><body><trans-unit id=""1""><source><![CDATA[!!translatable!!]]></source><target /></trans-unit></body></file></xliff>";

		internal static Dictionary<string, TranslatableAsset> GetTranslatableContent()
		{

			Dictionary<string, TranslatableAsset> result = new Dictionary<string, TranslatableAsset>();

			IssueList filteredIssues = GetIssueIDs();

			foreach (Issue issue in filteredIssues.issues)
			{
				string issues_query = String.Format("fields=description");
				string issue_json = jiraManager.RunQuery(JiraResource.issue, issues_query, null, "GET", issue.id);
				jiraIssue ji = Helper.Deserialize<jiraIssue>(issue_json);
				string translatable = ji.fields.description;
				string fileContent = xliffFrame.Replace("!!source!!", ConfigurationHelper.Config.xliffSource).Replace("!!target!!", ConfigurationHelper.Config.xliffTarget).Replace("!!translatable!!", translatable);
				Stream stream = Helper.GenerateStreamFromString(fileContent);
                result.Add(issue.key, new TranslatableAsset() { Key = issue.key, FileType = "xliff", Stream = stream });				
				SetIssueStatus(issue.key, ConfigurationHelper.Config.TransitionForStartingTranslation);
				Log.AddLog("Issue processed: " + issue.key);
			}

			return result;
		}

		

		internal static void DeliverTranslations(Dictionary<string, Stream> downloadedFiles)
		{
			foreach (string fileID in downloadedFiles.Keys)
			{
				string translation = (new StreamReader(downloadedFiles[fileID])).ReadToEnd();
				string sourceString = Regex.Match(translation, @"(?s)(?<=<source><!\[CDATA\[).*?(?=\]\]></source>)").Value;
				string translationString = Regex.Match(translation, @"(?s)(?<=<target><!\[CDATA\[).*?(?=\]\]></target>)").Value;

				string issue_post = @"{""update"": {""description"": [{""set"": """ + JsonEncode(sourceString) + @"\r\n-----\r\n" + JsonEncode(translationString) + @"""}]}}";
				string issue_json = jiraManager.RunQuery(JiraResource.issue, null, issue_post, "put", fileID);

				SetIssueStatus(fileID, ConfigurationHelper.Config.TransitionForFinishingTranslation);
				Log.AddLog("Issue delivered to JIRA: " + fileID);
			}
		}

		private static void SetIssueStatus(string issueID, string newStatus)
		{
			string issue_post = @"{""transition"": {""id"": """ + newStatus + @"""}}";
			string issue_json = jiraManager.RunQuery(JiraResource.issue, null, issue_post, "post", issueID + "/transitions");
		}

		private static string JsonEncode(string text)
		{
			string result = text.Replace(@"\", @"\\");
			result = Regex.Replace(result, @"[\r\n]+", @"\r\n");
			return result;
		}

		private static IssueList GetIssueIDs()
		{
			string issues_query = String.Format("jql={0}&startAt={1}&fields=id,key&fieldByKeys=true", ConfigurationHelper.Config.jiraApiQuery, "0");

			string issues_json = jiraManager.RunQuery(JiraResource.search, issues_query);
			IssueList filteredIssues = Helper.Deserialize<IssueList>(issues_json);

			while (filteredIssues.startAt + filteredIssues.maxResults < filteredIssues.total)
			{
				try
				{
					filteredIssues.startAt += filteredIssues.maxResults;
					Regex regex = new Regex(@"(?<start>startAt=)\d+", RegexOptions.IgnorePatternWhitespace | RegexOptions.ExplicitCapture);
					issues_query = regex.Replace(issues_query, "${start}" + filteredIssues.startAt.ToString());

					issues_json = jiraManager.RunQuery(JiraResource.search, issues_query);

					filteredIssues.Add(Helper.Deserialize<IssueList>(issues_json));

				}
				catch (ArgumentException ex)
				{
					Log.AddLog("There was a syntax error with a regular expression used in the JiraReporting program. " + ex.Message, MessageType.Error);
				}
			}

			return filteredIssues;

		}
	}
}