using System;
using System.Collections.Generic;
using System.IO;

namespace memoQSampleCMSConnector
{
	internal class TransferCMS2memoQ
	{
		private string projectID = "";

		public TransferCMS2memoQ()
		{
			ProcessTransfer();
		}

		private void ProcessTransfer()
		{
			try
			{
				Log.AddLog("Checking for new content in CMS...", MessageType.MajorInfo);
				Dictionary<string, TranslatableAsset> newCMSFiles = CheckForNewCMSFiles();  
				if (newCMSFiles.Count != 0)
				{
					OpenSessionFormQ();
					foreach (var newCMSFile in newCMSFiles)
					{
						UploadFileTomQ(newCMSFile);
					}
					SendSessionForTranslation();
					Log.AddLog("Translatable files transferred to memoQ.", MessageType.MajorInfo);
				}
				else
				{
					Log.AddLog("No new files for translation.", MessageType.MajorInfo);
				}
			}
			catch (Exception ex)
			{
				Log.AddLog("CMS to memoQ transfer error: " + ex.Message, MessageType.Error);
			}
		}

		private Dictionary<string, TranslatableAsset> CheckForNewCMSFiles()
		{
			return CMS_Session.GetTranslatableContent();
		}

		private void OpenSessionFormQ()
		{
			try
			{
				projectID = "";
				Log.AddLog("Getting existing CMS Dashboard projects");
				ProjectInfo pi = mQCMSAPI_Session.GetProjects();
				Log.AddLog("Existing CMS Dashboard projects loaded");

				if (pi == null)
				{
					string projectName = "ProjectName_" + Guid.NewGuid().ToString().Substring(0, 4);
					projectID = mQCMSAPI_Session.CreateNewProject(projectName);
					Log.AddLog("Session created: " + projectName + " - " + projectID);
				}
				else
				{
					projectID = pi.ClientProjectId;
					Log.AddLog("Open session found: " + pi.Name + " - " + projectID);
				}
			}
			catch (Exception ex)
			{
				Log.AddLog("Session creation error: " + ex.Message + " - " + ex.StackTrace, MessageType.Error);
			}
		}

		private void UploadFileTomQ(KeyValuePair<string, TranslatableAsset> newCMSFile)
		{
			try
			{
				if (!string.IsNullOrEmpty(projectID))
				{
					string jobName = newCMSFile.Key;   // the file's ID from the CMS, e.g. file name
					int jobID = mQCMSAPI_Session.UploadJob(projectID, jobName, newCMSFile.Value);
					Log.AddLog("Job added: " + jobName);
				}
				else
				{
					Log.AddLog("Session not initialized", MessageType.Warning);
				}
			}
			catch (Exception ex)
			{
				Log.AddLog("File upload to CMS API error: " + ex.Message + " - " + ex.StackTrace, MessageType.Error);
			}
		}

		private void SendSessionForTranslation()
		{
			try
			{
				if (!string.IsNullOrEmpty(projectID))
				{
					mQCMSAPI_Session.SendProject(projectID);
					Log.AddLog("Session sent for translation: " + projectID);
				}
				else
				{
					Log.AddLog("Session not initialized", MessageType.Warning);
				}
			}
			catch (Exception ex)
			{
				Log.AddLog("Project creation error: " + ex.Message, MessageType.Error);
			}
		}
	}
}