using System.Net.Security;
using System.Net;
using System;
using System.Collections.Generic;
using System.Text;
using System.Web.Script.Serialization;
using System.IO;
using System.Globalization;

namespace memoQSampleCMSConnector
{
	internal class mQCMSAPI_Session
	{
		private static JavaScriptSerializer serializer = new JavaScriptSerializer();

		internal static ProjectInfo GetProjects()
		{

			string response = mQCMSAPICommInterface.SendRequest(null, "GET", "/projects", false);
			ProjectInfo[] projectList = serializer.Deserialize<ProjectInfo[]>(response);
			foreach (ProjectInfo pi in projectList)
			{
				if (pi.Status == "Created")
					return pi;
			}

			return null;
		}

		internal static string CreateNewProject(string projectName)
		{

			ProjectCreateInfo pci = new ProjectCreateInfo()
			{
				CallbackUrl = "string",
				Deadline = (DateTime.Now + new TimeSpan(30, 0, 0, 0)).ToString(CultureInfo.CurrentCulture.DateTimeFormat.UniversalSortableDateTimePattern),
				Name = projectName
			};

			string postData = serializer.Serialize(pci);
			string response = mQCMSAPICommInterface.SendRequest(Encoding.UTF8.GetBytes(postData), "POST", "/projects", false);
			ProjectInfo projectInfo = serializer.Deserialize<ProjectInfo>(response);
			return projectInfo.ClientProjectId;
		}

        internal static int UploadJob(string projectID, string jobName, TranslatableAsset newCMSFile)
        {
            TranslationJobCreateInfo tjci = new TranslationJobCreateInfo()
            {
                Name = jobName,
                SourceLang = ConfigurationHelper.Config.memoQSource,
                TargetLang = ConfigurationHelper.Config.memoQTarget,
                Url = ""
            };

            Dictionary<string, object> newFileToAdd;

            switch (ConfigurationHelper.Config.mode) {                 
                case Mode.Virtual:
                    if (ConfigurationHelper.Config.UseFileType)
                    {
                        tjci.FileType = newCMSFile.FileType;
                    }
                    MemoryStream ms = new MemoryStream();
                    ms.SetLength(newCMSFile.Stream.Length);
                    newCMSFile.Stream.Read(ms.GetBuffer(), 0, (int)newCMSFile.Stream.Length);
                    newFileToAdd = new Dictionary<string, object>()
                    {
                        { "translationJob", tjci},
                        { "file", new FileParameter(ms.ToArray(), jobName, "application/octet-stream") }
                    };
                    break;
                case Mode.Jira:
                default:
                    tjci.FileType = "xliff";
                    newFileToAdd = new Dictionary<string, object>()
                    {
                        { "translationJob", tjci},
                        { "file", new FileParameter(((MemoryStream)newCMSFile.Stream).ToArray(), jobName, "text/plain") }
                    };
                    break;                    
            }
           

			string response = mQCMSAPICommInterface.MultipartFormDataPost(projectID, newFileToAdd);
			TranslationJobInfo tjInfo = serializer.Deserialize<TranslationJobInfo>(response);
			return tjInfo.TranslationJobId;
		}

		internal static void SendProject(string projectID)
		{
			ChangeStatus cps = new ChangeStatus()
			{
				NewStatus = "Committed"
			};
			string postData = serializer.Serialize(cps);
			string response = mQCMSAPICommInterface.SendRequest(Encoding.ASCII.GetBytes(postData), "PATCH", "/projects/" + projectID, false);
			Log.AddLog("Project committed: " + projectID);
		}

		internal static Dictionary<string, Stream> GetTranslations()
		{
			Dictionary<string, Stream> downloadedFiles = new Dictionary<string, Stream>();

			string responseProjects = mQCMSAPICommInterface.SendRequest(null, "GET", "/projects", false);
			ProjectInfo[] projectList = serializer.Deserialize<ProjectInfo[]>(responseProjects);

			foreach (ProjectInfo pi in projectList)
			{
				if (pi.Status == "Committed")
				{
					string responseJobs = mQCMSAPICommInterface.SendRequest(null, "GET", "/projects/" + pi.ClientProjectId + "/jobs", false);
					TranslationJobInfo[] jobList = serializer.Deserialize<TranslationJobInfo[]>(responseJobs);
					foreach (TranslationJobInfo tji in jobList)
					{
						if (tji.Status == "TranslationReady")
						{
							string responseTranslation = mQCMSAPICommInterface.SendRequest(null, "GET", "/jobs/" + tji.TranslationJobId + "/translation", true);

							downloadedFiles.Add(tji.Name, Helper.GenerateStreamFromString(responseTranslation));

							ChangeStatus cjs = new ChangeStatus()
							{
								NewStatus = "DeliveredToSource"
							};
							string postData = serializer.Serialize(cjs);
							string responsePatchJob = mQCMSAPICommInterface.SendRequest(Encoding.ASCII.GetBytes(postData), "PATCH", "/jobs/" + tji.TranslationJobId, false);
							Log.AddLog("Job downloaded from project " + pi.Name + "-" + pi.ClientProjectId + " - job name: " + tji.Name);
						}
					}
				}
			}

			return downloadedFiles;
		}
	}
}