using System;
using System.IO;
using System.Text;
using System.Net;

namespace memoQSampleCMSConnector
{
    public class Config
    {
        public string cmsApiUrl { get; set; }
        public string cmsApiSecret { get; set; }
        public int[] loggingLevels { get; set; }

		public string jiraApiUrl { get; set; }
		public string jiraApiUser { get; set; }
		public string jiraApiPassword { get; set; }
		public string jiraApiQuery { get; set; }

		public string xliffSource { get; set; }
		public string xliffTarget { get; set; }
		internal string memoQSource { get; set; }
		internal string memoQTarget { get; set; }

        internal string InputFolder { get; set; }
        internal string InputFolderPath { get; set; }

        internal string OutputFolder { get; set; }
        internal string OutputFolderPath { get; set; }

        internal string TransitionForStartingTranslation { get; set; }
		internal string TransitionForFinishingTranslation { get; set; }

        internal bool UseFileType { get; set; }

        public string errorMessage;
        internal bool isSPTset;
        internal SecurityProtocolType securityProtocolType;

		public string xliffFilePath { get; set; }
		public Mode mode { get; set; }

        public Config()
        {
            // Default values
            cmsApiUrl = "<service endpoint address provided by memoQ>";
            cmsApiSecret = "CMSGATEWAY-API <connection key provided by memoQ>";
            loggingLevels = new int[] { 1, 1, 1, 1 };
            errorMessage = "";
            isSPTset = false;
			jiraApiUrl = "https://<jira-url>/rest/api/latest/";
			jiraApiUser = "<user@domain.com>";
			jiraApiPassword = "<password for the uer>";
			jiraApiQuery = @"<Jira filter like this: Project = ""Jira - memoQ Integration Test"" AND status = ""To Do"">";
            xliffSource = "<2-letter or 2+2 letter XLIFF-compatible source language code like en or en-us>";
            xliffTarget = "<2-letter or 2+2 letter XLIFF-compatible target language code like fr or fr-CA>";
			memoQSource = "<3-letter or 3+2 letter memoQ-compatible source language code like ger>";
			memoQTarget = "<3-letter or 3+2 letter memoQ-compatible target language code like eng-us>";
            InputFolder = @"%USERPROFILE%\Desktop\CMS Sample Client Store";
            UseFileType = true;
            TransitionForStartingTranslation = "11";
			TransitionForFinishingTranslation = "21";
		}
	}

    public static class ConfigurationHelper
    {
        private const string ConfigurationFolderPath =
            @"%USERPROFILE%\AppData\Local\memoQ Sample CMS Connector\";
        private const string ConfigurationFileName = "memoQ Sample CMS Connector.config";
        public static DirectoryInfo ConfigurationFolder;
        public static FileInfo ConfigurationFile;
        public static Config Config;
		public static string realConfigFilePath;

        public static bool Initialize()
        {
            try
            {
                realConfigFilePath = Environment.ExpandEnvironmentVariables(ConfigurationFolderPath);                

                if (!Directory.Exists(realConfigFilePath))
                    ConfigurationFolder = Directory.CreateDirectory(realConfigFilePath);
                else
                    ConfigurationFolder = new DirectoryInfo(realConfigFilePath);

                Config = new Config();

                ConfigurationFile = new FileInfo(Path.Combine(ConfigurationFolder.FullName, ConfigurationFileName));
                if (File.Exists(ConfigurationFile.FullName))
                    return ReadConfigurationFile();
                else
                    return WriteConfigurationFile();
            }
            catch (Exception ex)
            {
                Config.errorMessage = ex.Message;
                return false;
            }
        }

        public static bool SaveChanges()
        {
            Config.errorMessage = "";
            return WriteConfigurationFile();
        }

        private static bool ReadConfigurationFile()
        {
            try
            {
                using (TextReader rd = new StreamReader(ConfigurationFile.FullName, Encoding.UTF8))
                {
                    string line = "";
                    rd.ReadLine();
                    while ((line = rd.ReadLine()) != null)
                    {
                        var d = new string[] { "" };

                        try
                        {
                            d = new string[] { line.Substring(0, line.IndexOf('=')), line.Substring(line.IndexOf('=') + 1) };
                        } catch { }

                        if (d.Length == 2)
                        {
                            switch (d[0])
                            {
                                case "cmsApiUrl":
                                    Config.cmsApiUrl = d[1];
                                    break;
                                case "cmsApiSecret":
                                    Config.cmsApiSecret = d[1];
                                    break;
								case "jiraApiUrl":
									Config.jiraApiUrl = d[1];
									break;
								case "jiraApiUser":
									Config.jiraApiUser = d[1];
									break;
								case "jiraApiPassword":
									Config.jiraApiPassword = d[1];
									break;
								case "jiraApiQuery":
									Config.jiraApiQuery = d[1];
									break;
								case "xliffSource":
									Config.xliffSource = d[1];
									break;
								case "xliffTarget":
									Config.xliffTarget = d[1];
									break;
								case "memoQSource":
									Config.memoQSource = d[1];
									break;
								case "memoQTarget":
									Config.memoQTarget = d[1];
									break;
                                case "inputFolder":
                                    Config.InputFolder = d[1];
                                    Config.InputFolderPath = Environment.ExpandEnvironmentVariables(Config.InputFolder);
                                    Config.OutputFolder = Config.InputFolder + "\\Output\\";
                                    Config.OutputFolderPath = Config.InputFolderPath + "\\Output\\";
                                    break;
                                case "TransitionForStartingTranslation":
									Config.TransitionForStartingTranslation = d[1];
									break;
								case "TransitionForFinishingTranslation":
									Config.TransitionForFinishingTranslation = d[1];
									break;
								case "loggingLevels":
                                    char[] loggedLevels = d[1].ToCharArray();
                                    Config.loggingLevels = new int[] { Convert.ToInt32(loggedLevels[0].ToString()), Convert.ToInt32(loggedLevels[1].ToString()),
                                        Convert.ToInt32(loggedLevels[2].ToString()), Convert.ToInt32(loggedLevels[3].ToString()) };
                                    break;
                                case "SecurityProtocolType":
                                    Config.isSPTset = true;
                                    switch (d[1])
                                    {
                                        case "ssl3":
                                            Config.securityProtocolType = SecurityProtocolType.Ssl3;
                                            break;
                                        case "tls":
                                            Config.securityProtocolType = SecurityProtocolType.Tls;
                                            break;
                                        case "tls11":
                                            Config.securityProtocolType = SecurityProtocolType.Tls11;
                                            break;
                                        case "tls12":
                                            Config.securityProtocolType = SecurityProtocolType.Tls12;
                                            break;
                                        default:
                                            Config.isSPTset = false;
                                            break;
                                    }
                                    break;
                                default:
                                    break;
                            }
                        }
                    }
                }
                return true;
            }
            catch (Exception ex)
            {
                Config.errorMessage = ex.Message + " - Config file: " + ConfigurationFile.FullName;
                return false;
            }
        }

        private static bool WriteConfigurationFile()
        {
            try
            {
                using (TextWriter wr = new StreamWriter(ConfigurationFile.FullName, false, Encoding.UTF8))
                {
                    wr.WriteLine("[memoQ Sample CMS Connector Settings]");
                    if (Config != null)
                    {
                        wr.WriteLine("cmsApiUrl=" + Config.cmsApiUrl);
                        wr.WriteLine("cmsApiSecret=" + Config.cmsApiSecret);
                        wr.WriteLine();

                        wr.WriteLine("[Jira Mode Settings]");
                        wr.WriteLine("jiraApiUrl=" + Config.jiraApiUrl);
						wr.WriteLine("jiraApiUser=" + Config.jiraApiUser);
						wr.WriteLine("jiraApiPassword=" + Config.jiraApiPassword);
						wr.WriteLine("jiraApiQuery=" + Config.jiraApiQuery);

						wr.WriteLine("xliffSource=" + Config.xliffSource);
						wr.WriteLine("xliffTarget=" + Config.xliffTarget);

						wr.WriteLine("memoQSource=" + Config.memoQSource);
						wr.WriteLine("memoQTarget=" + Config.memoQTarget);

                        wr.WriteLine("TransitionForStartingTranslation=" + Config.TransitionForStartingTranslation);
						wr.WriteLine("TransitionForFinishingTranslation=" + Config.TransitionForFinishingTranslation);

						wr.WriteLine("loggingLevels=" + Config.loggingLevels[0].ToString() + Config.loggingLevels[1].ToString() + Config.loggingLevels[2].ToString() + Config.loggingLevels[3].ToString());
						
						if (Config.isSPTset)
                        {
                            string spt = "";

                            switch (Config.securityProtocolType)
                            {
                                case SecurityProtocolType.Ssl3:
                                    spt = "ssl3";
                                    break;
                                case SecurityProtocolType.Tls:
                                    spt = "tls";
                                    break;
                                case SecurityProtocolType.Tls11:
                                    spt = "tls11";
                                    break;
                                case SecurityProtocolType.Tls12:
                                    spt = "tls12";
                                    break;
                                default:
                                    break;
                            }
                            if (spt != "") wr.WriteLine("SecurityProtocolType=" + spt);
                        }

                        wr.WriteLine();

                        wr.WriteLine("[File System Mode Settings]");
                        wr.WriteLine("inputFolder=" + Config.InputFolderPath);

                    }
                }
                return true;
            }
            catch (Exception ex)
            {
                Config.errorMessage = ex.Message + " - Config file: " + ConfigurationFile.FullName;
                return false;
            }
        }

    }

	public enum Mode { Virtual, Jira  };
}