using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Threading;
using System.Windows.Forms;
using MemoQServicesClient.TMService;
using System.ServiceModel;
using MemoQServicesClient.TBService;
using MemoQServicesClient.SecurityService;
using System.IO;
using System.Diagnostics;
using MemoQServicesClient.TB;

namespace MemoQServicesClient
{
    public partial class MainForm : Form
    {
        public MainForm()
        {
            InitializeComponent();
            Log.Init(this.tbLog);
        }

        private void clearLogToolStripMenuItem_Click(object sender, EventArgs e)
        {
            tbLog.Clear();
        }

        #region TM management

        private void tmList()
        {
            Log.WriteMajorSeparatorLine();
            Log.WriteLine("ListTM called:");
            Log.WriteMinorSeparatorLine();
            TMServiceClient proxy = new TMServiceClient();
            TMInfo[] tmInfos = proxy.ListTMs(null, null);
            Log.Write(TMInfo.CollectionToString(tmInfos));
            Log.WriteMajorSeparatorLine();
        }

        private void tmExportTMX(int p)
        {
            Log.WriteMajorSeparatorLine();
            Log.WriteLine("Exporting TM #" + ((int)(p + 1)).ToString() + " to TMX:");
            TMServiceClient proxy = new TMServiceClient();
            TMInfo[] tmInfos = proxy.ListTMs(null, null);
            if (p >= tmInfos.Length)
            {
                Log.WriteLine("Error. No TM exist in the list at this position.");
                Log.WriteMajorSeparatorLine();
                return;
            }
            using (SaveFileDialog sfd = new SaveFileDialog())
            {
                sfd.OverwritePrompt = true;
                sfd.Filter = "TMX file|*.tmx";
                sfd.DefaultExt = ".tmx";
                if (sfd.ShowDialog() == DialogResult.OK)
                {
                    string filename = sfd.FileName;
                    Log.WriteLine("Exporting to: " + filename);
                    DateTime begin = DateTime.Now;
                    Guid sessionId = proxy.BeginChunkedTMXExport(tmInfos[p].Guid);
                    try
                    {
                        using (System.IO.FileStream fs = System.IO.File.Create(filename))
                        {
                            System.IO.BinaryWriter bw = new System.IO.BinaryWriter(fs);
                            byte[] buffer;
                            while ((buffer = proxy.GetNextTMXChunk(sessionId)) != null)
                                bw.Write(buffer);
                            bw.Flush();
                            bw.Close();
                        }
                    }
                    finally
                    {
                        proxy.EndChunkedTMXExport(sessionId);
                    }
                    DateTime end = DateTime.Now;
                    Log.WriteLine(string.Format("Duration: {0} sec", ((TimeSpan)(end - begin)).TotalSeconds));
                    Log.WriteLine("Done.");
                }
                else
                    Log.WriteLine("cancelled");
                Log.WriteMajorSeparatorLine();
            }
        }

        private void tmImportTMX(int p)
        {
            Log.WriteMajorSeparatorLine();
            Log.WriteLine("Importing TMX into TM #" + ((int)(p + 1)).ToString() + ":");
            TMServiceClient proxy = new TMServiceClient();
            TMInfo[] tmInfos = proxy.ListTMs(null, null);
            if (p >= tmInfos.Length)
            {
                Log.WriteLine("Error. No TM exist in the list at this position.");
                Log.WriteMajorSeparatorLine();
                return;
            }
            using (OpenFileDialog ofd = new OpenFileDialog())
            {
                ofd.CheckFileExists = true;
                ofd.Filter = "TMX file|*.tmx";
                if (ofd.ShowDialog() == DialogResult.OK)
                {
                    Guid sessionId = Guid.Empty;
                    TmxImportResult res = null;
                    DateTime begin = DateTime.Now;
                    try
                    {
                        string filename = ofd.FileName;
                        Log.WriteLine("Importing from: " + filename);

                        sessionId = proxy.BeginChunkedTMXImport(tmInfos[p].Guid);
                        using (System.IO.StreamReader sr = new System.IO.StreamReader(filename, true))
                        {
                            char[] buffer = new char[10000];
                            byte[] bbuffer;
                            while (true)
                            {
                                int readCharsCount = sr.Read(buffer, 0, 10000);
                                if (readCharsCount == 0)
                                    break;
                                bbuffer = Encoding.GetEncoding("UTF-16").GetBytes(buffer, 0, readCharsCount);
                                proxy.AddNextTMXChunk(sessionId, bbuffer);
                            }
                            sr.Close();
                        }
                    }
                    finally
                    {
                        if (sessionId != Guid.Empty)
                            res = proxy.EndChunkedTMXImport(sessionId);

                    }

                    DateTime end = DateTime.Now;
                    Log.WriteLine(string.Format("successfully imported {0} entries of {1}.", res.ImportedSegmentCount, res.AllSegmentCount));
                    Log.WriteLine(string.Format("Duration: {0} sec", ((TimeSpan)(end - begin)).TotalSeconds));
                    Log.WriteLine("Done.");
                }
                else
                    Log.WriteLine("cancelled");
                Log.WriteMajorSeparatorLine();
            }
        }

        private void tmCreateAndPublish()
        {
            Log.WriteMajorSeparatorLine();
            Log.WriteLine("Create TM called:");
            TMInfo tmInfo = new TMInfo(Guid.Empty, "testTMName - " + DateTime.Now.ToString("yyyyMMdd_hhmmss"), "testDesc", false,
                false, false, false, "eng", "hun");

            TMServiceClient proxy = new TMServiceClient();
            Guid guid = proxy.CreateAndPublish(tmInfo);
            Log.WriteLine("The guid of the newly created TM is: " + guid.ToString());
            Log.WriteMajorSeparatorLine();
        }

        private void tmDelete(int p)
        {
            Log.WriteMajorSeparatorLine();
            Log.WriteLine("Deleting TM #" + ((int)(p + 1)).ToString() + ":");
            TMServiceClient proxy = new TMServiceClient();
            TMInfo[] tmInfos = proxy.ListTMs(null, null);
            if (p >= tmInfos.Length)
            {
                Log.WriteLine("Error. No TM exist in the list at this position.");
                Log.WriteMajorSeparatorLine();
                return;
            }
            proxy.DeleteTM(tmInfos[p].Guid);
            Log.WriteLine("Done.");
            Log.WriteMajorSeparatorLine();
        }

        private void tmLookup(Guid tmGuid, string lookupText)
        {
            Log.WriteMajorSeparatorLine();
            Log.WriteLine("Lookup in TM:");
            using (var proxy = new TMServiceClient())
            {
                var xmlDoc = "<?xml version=\"1.0\" encoding=\"utf-16\"?>";
                xmlDoc += "<mq:lookup xmlns:mq=\"http://kilgray.com/memoqservices/2007\">";
                xmlDoc += @"<mq:lookup-item>";
                xmlDoc += @"<mq:context></mq:context>";
                xmlDoc += @"<seg>";
                xmlDoc += System.Security.SecurityElement.Escape(lookupText);
                xmlDoc += @"</seg>";
                xmlDoc += @"</mq:lookup-item>";
                xmlDoc += @"</mq:lookup>";

                var response = proxy.LookupSegment(currentSessionId, xmlDoc, tmGuid, new LookupSegmentRequest()
                        {
                            InlineTagStrictness = InlineTagStrictness.Permissive,
                            MatchThreshold = 60,
                            OnlyBest = false,
                            AdjustFuzzyMatches = true
                        });

                Log.WriteLine(response);
            }
            Log.WriteLine("Done.");
            Log.WriteMajorSeparatorLine();
        }

        private void tmConcordance(Guid tmGuid, string searchString)
        {
            Log.WriteMajorSeparatorLine();
            Log.WriteLine("Concordance in TM:");
            using (var proxy = new TMServiceClient())
            {
                var response = proxy.Concordance(currentSessionId, searchString, tmGuid, new ConcordanceRequest()
                    {
                        CaseSensitive = false,
                        NumericEquivalence = false,
                        ResultsLimit = 25,
                        ReverseLookup = false
                    });
                Log.WriteLine(response);
            }
            Log.WriteLine("Done.");
            Log.WriteMajorSeparatorLine();
        }

        private void tmAddUpdateEntry(Guid tmGuid, string segmentText)
        {
            Log.WriteMajorSeparatorLine();
            Log.WriteLine("Add/update entry to TM:");
            using (var proxy = new TMServiceClient())
            {
                var xmlDoc = "<?xml version=\"1.0\" encoding=\"utf-16\"?>";
                xmlDoc += "<mq:item-to-store xmlns:mq=\"http://kilgray.com/memoqservices/2007\">";
                xmlDoc += @"<mq:context-pre>" + "pre--" + System.Security.SecurityElement.Escape(segmentText) + "</mq:context-pre>";
                xmlDoc += @"<mq:context-post>" + "post--" + System.Security.SecurityElement.Escape(segmentText) + "</mq:context-post>";
                xmlDoc += @"<mq:seg-source>";
                xmlDoc += System.Security.SecurityElement.Escape(segmentText);
                xmlDoc += @"</mq:seg-source>";
                xmlDoc += @"<mq:seg-target>";
                xmlDoc += System.Security.SecurityElement.Escape(segmentText + segmentText);
                xmlDoc += @"</mq:seg-target>";
                xmlDoc += "<prop type=\"tmattrib\">" + "prop--" + segmentText + "</prop>";
                xmlDoc += @"</mq:item-to-store>";

                proxy.AddOrUpdateEntry(currentSessionId, xmlDoc, tmGuid);
            }
            Log.WriteLine("Done.");
            Log.WriteMajorSeparatorLine();
        }

        #region TM menuitems event handlers

        private void tmCreateAndPublishToolStripMenuItem_Click(object sender, EventArgs e)
        {
            try
            {
                tmCreateAndPublish();
            }
            catch (FaultException ex)
            {
                if (ex.Code.Name == "Server.Expected")
                    MessageBox.Show("Expected exception. The following message can be displayed to the user: \n\n" +
                        ex.Message);
                else
                {
                    MessageBox.Show("Unexpected exception. See server log for details.");
                }
            }
        }

        private void listTMsToolStripMenuItem_Click(object sender, EventArgs e)
        {
            try
            {
                tmList();
            }
            catch (FaultException ex)
            {
                if (ex.Code.Name == "Server.Expected")
                    MessageBox.Show("Expected exception. The following message can be displayed to the user: \n\n" +
                        ex.Message);
                else
                {
                    MessageBox.Show("Unexpected exception. See server log for details.");
                }
            }
        }

        private void importTMXTo1TMToolStripMenuItem_Click(object sender, EventArgs e)
        {
            try
            {
                tmImportTMX(1);
            }
            catch (FaultException ex)
            {
                if (ex.Code.Name == "Server.Expected")
                    MessageBox.Show("Expected exception. The following message can be displayed to the user: \n\n" +
                        ex.Message);
                else
                {
                    MessageBox.Show("Unexpected exception. See server log for details.");
                }
            }
        }

        private void importTMXTo1TMToolStripMenuItem1_Click(object sender, EventArgs e)
        {
            try
            {
                tmImportTMX(2);
            }
            catch (FaultException ex)
            {
                if (ex.Code.Name == "Server.Expected")
                    MessageBox.Show("Expected exception. The following message can be displayed to the user: \n\n" +
                        ex.Message);
                else
                {
                    MessageBox.Show("Unexpected exception. See server log for details.");
                }
            }
        }
        private void exportToTMXToolStripMenuItem_Click(object sender, EventArgs e)
        {
            try
            {
                tmExportTMX(0);
            }
            catch (FaultException ex)
            {
                if (ex.Code.Name == "Server.Expected")
                    MessageBox.Show("Expected exception. The following message can be displayed to the user: \n\n" +
                        ex.Message);
                else
                    MessageBox.Show("Unexpected exception. See MemoQ server log for details.\nMessage: "
                        + ex.Message);
            }
        }

        private void exportTM1ToTMXToolStripMenuItem_Click(object sender, EventArgs e)
        {
            try
            {
                tmExportTMX(1);
            }
            catch (FaultException ex)
            {
                if (ex.Code.Name == "Server.Expected")
                    MessageBox.Show("Expected exception. The following message can be displayed to the user: \n\n" +
                        ex.Message);
                else
                    MessageBox.Show("Unexpected exception. See MemoQ server log for details.\nMessage: "
                        + ex.Message);
            }
        }

        private void exportTM1ToTMXToolStripMenuItem1_Click(object sender, EventArgs e)
        {
            try
            {
                tmExportTMX(2);
            }
            catch (FaultException ex)
            {
                if (ex.Code.Name == "Server.Expected")
                    MessageBox.Show("Expected exception. The following message can be displayed to the user: \n\n" +
                        ex.Message);
                else
                    MessageBox.Show("Unexpected exception. See MemoQ server log for details.\nMessage: "
                        + ex.Message);
            }
        }

        private void importTM1ToTMXToolStripMenuItem_Click(object sender, EventArgs e)
        {
            try
            {
                tmImportTMX(0);
            }
            catch (FaultException ex)
            {
                if (ex.Code.Name == "Server.Expected")
                    MessageBox.Show("Expected exception. The following message can be displayed to the user: \n\n" +
                        ex.Message);
                else
                {
                    MessageBox.Show("Unexpected exception. See server log for details.");
                }
            }
        }

        private void deleteTM1ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            try
            {
                tmDelete(0);
            }
            catch (FaultException ex)
            {
                if (ex.Code.Name == "Server.Expected")
                    MessageBox.Show("Expected exception. The following message can be displayed to the user: \n\n" +
                        ex.Message);
                else
                {
                    MessageBox.Show("Unexpected exception. See server log for details.");
                }
            }
        }

        private void deleteTM2ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            try
            {
                tmDelete(1);
            }
            catch (FaultException ex)
            {
                if (ex.Code.Name == "Server.Expected")
                    MessageBox.Show("Expected exception. The following message can be displayed to the user: \n\n" +
                        ex.Message);
                else
                {
                    MessageBox.Show("Unexpected exception. See server log for details.");
                }
            }
        }

        private void deleteTM3ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            try
            {
                tmDelete(2);
            }
            catch (FaultException ex)
            {
                if (ex.Code.Name == "Server.Expected")
                    MessageBox.Show("Expected exception. The following message can be displayed to the user: \n\n" +
                        ex.Message);
                else
                {
                    MessageBox.Show("Unexpected exception. See server log for details.");
                }
            }
        }

        private void lookupInTMToolStripMenuItem_Click(object sender, EventArgs e)
        {
            try
            {
                using (var f = new TM.LookupForm())
                {
                    f.TMList = new TMServiceClient().ListTMs(null, null);
                    if (f.ShowDialog(this) == System.Windows.Forms.DialogResult.OK)
                        tmLookup(f.TMGuid, f.SegmentText);
                }
            }
            catch (FaultException ex)
            {
                if (ex.Code.Name == "Server.Expected")
                    MessageBox.Show("Expected exception. The following message can be displayed to the user: \n\n" +
                        ex.Message);
                else
                {
                    MessageBox.Show("Unexpected exception. See server log for details.");
                }
            }
        }

        private void concordanceInTMToolStripMenuItem_Click(object sender, EventArgs e)
        {
            try
            {
                using (var f = new TM.LookupForm())
                {
                    f.TMList = new TMServiceClient().ListTMs(null, null);
                    if (f.ShowDialog(this) == System.Windows.Forms.DialogResult.OK)
                        tmConcordance(f.TMGuid, f.SegmentText);
                }
            }
            catch (FaultException ex)
            {
                if (ex.Code.Name == "Server.Expected")
                    MessageBox.Show("Expected exception. The following message can be displayed to the user: \n\n" +
                        ex.Message);
                else
                {
                    MessageBox.Show("Unexpected exception. See server log for details.");
                }
            }
        }

        private void addupdateEntryToTMToolStripMenuItem_Click(object sender, EventArgs e)
        {
            try
            {
                using (var f = new TM.LookupForm())
                {
                    f.TMList = new TMServiceClient().ListTMs(null, null);
                    if (f.ShowDialog(this) == System.Windows.Forms.DialogResult.OK)
                        tmAddUpdateEntry(f.TMGuid, f.SegmentText);
                }
            }
            catch (FaultException ex)
            {
                if (ex.Code.Name == "Server.Expected")
                    MessageBox.Show("Expected exception. The following message can be displayed to the user: \n\n" +
                        ex.Message);
                else
                {
                    MessageBox.Show("Unexpected exception. See server log for details.");
                }
            }
        }

        private void repairTM1ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            try
            {
                var tmServiceTest = new TMServiceTest();
                tmServiceTest.RepairTM(0);
            }
            catch (FaultException ex)
            {
                if (ex.Code.Name == "Server.Expected")
                    MessageBox.Show("Expected exception. The following message can be displayed to the user: \n\n" +
                        ex.Message);
                else
                {
                    MessageBox.Show("Unexpected exception. See server log for details.");
                }
            }
        }

        private void repairTM2ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            try
            {
                var tmServiceTest = new TMServiceTest();
                tmServiceTest.RepairTM(1);
            }
            catch (FaultException ex)
            {
                if (ex.Code.Name == "Server.Expected")
                    MessageBox.Show("Expected exception. The following message can be displayed to the user: \n\n" +
                        ex.Message);
                else
                {
                    MessageBox.Show("Unexpected exception. See server log for details.");
                }
            }
        }

        private void repairTM3ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            try
            {
                var tmServiceTest = new TMServiceTest();
                tmServiceTest.RepairTM(2);
            }
            catch (FaultException ex)
            {
                if (ex.Code.Name == "Server.Expected")
                    MessageBox.Show("Expected exception. The following message can be displayed to the user: \n\n" +
                        ex.Message);
                else
                {
                    MessageBox.Show("Unexpected exception. See server log for details.");
                }
            }
        }

        #endregion

        #endregion

        #region Security

        /// <summary>
        /// The current session ID of the logon session to memoQ server; if any. Null means no session.
        /// </summary>
        private string currentSessionId = null;

        #region  UserManagement

        private void listUsersToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Log.WriteMajorSeparatorLine();
            Log.WriteLine("ListUsers called:");
            Log.WriteMinorSeparatorLine();
            SecurityServiceClient proxy = new SecurityServiceClient();
            try
            {
                UserInfo[] userInfos = proxy.ListUsers();
                Log.Write(UserInfo.CollectionToString(userInfos));
            }
            catch (Exception ex)
            {
                Log.WriteLine(ex.Message);
            }
            Log.WriteMajorSeparatorLine();
        }

        private void getUserToolStripMenuItem_Click(object sender, EventArgs e)
        {
            using (ParameterSettingsForm form = new ParameterSettingsForm(SettingsMode.User))
            {
                if (form.ShowDialog() == DialogResult.OK)
                {
                    Guid guid = form.guid;
                    Log.WriteMajorSeparatorLine();
                    Log.WriteLine("GetUser " + guid.ToString() + ":");
                    Log.WriteMinorSeparatorLine();
                    SecurityServiceClient proxy = new SecurityServiceClient();
                    try
                    {
                        UserInfo userInfo = proxy.GetUser(guid);
                        if (userInfo != null)
                        {
                            Log.WriteLine(userInfo.ToString());
                        }
                        else Log.WriteLine("User guid does not exist");
                    }
                    catch (Exception ex)
                    {
                        Log.WriteLine(ex.Message);
                    }
                    Log.WriteMajorSeparatorLine();
                }
            }
        }

        const string salt = "fgad s d f sgds g  sdg gfdg";

        private void createUserToolStripMenuItem_Click(object sender, EventArgs e)
        {
            using (NameSettingForm form = new NameSettingForm(NameSettingMode.User))
            {
                if (form.ShowDialog() == DialogResult.OK)
                {
                    string passwordFromUser = "pw";
                    string hashedPW = HashPassword(passwordFromUser);

                    string name = form.name;
                    Log.WriteMajorSeparatorLine();
                    Log.WriteLine("CreateUser called:");
                    UserInfo userInfo = new UserInfo(Guid.NewGuid(),
                        name, hashedPW, false, name + "Test User", name + "Adr1", name + "Em1", name + "pn1", name + "mpn1");
                    SecurityServiceClient proxy = new SecurityServiceClient();
                    Guid guid;
                    try
                    {
                        guid = proxy.CreateUser(userInfo);
                        Log.WriteLine("The guid of the newly created user is: " + guid.ToString());

                    }
                    catch (Exception ex)
                    {
                        Log.WriteLine(ex.Message);
                    }
                    Log.WriteMajorSeparatorLine();
                }
            }
        }

        void CreateUser()
        {

        }

        public static string HashPassword(string password)
        {
            return System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(password + salt, "sha1");
        }

        private void updateUserToolStripMenuItem_Click(object sender, EventArgs e)
        {
            using (ParameterSettingsForm form = new ParameterSettingsForm(SettingsMode.User))
            {
                if (form.ShowDialog() == DialogResult.OK)
                {
                    Guid guid = form.guid;
                    Log.WriteMajorSeparatorLine();
                    Log.WriteLine("UpdateUser " + guid.ToString() + ":");
                    SecurityServiceClient proxy = new SecurityServiceClient();
                    try
                    {
                        UserInfo userInfo = proxy.GetUser(guid);
                        userInfo.UserName = userInfo.UserName + "_U";
                        userInfo.IsDisabled = !userInfo.IsDisabled;
                        userInfo.Address = userInfo.Address + "_U";
                        userInfo.EmailAddress = userInfo.EmailAddress + "_U";
                        userInfo.FullName = userInfo.FullName + "_U";
                        userInfo.MobilePhoneNumber = userInfo.MobilePhoneNumber + "_U";
                        userInfo.PhoneNumber = userInfo.PhoneNumber + "_U";

                        proxy.UpdateUser(userInfo);
                        Log.WriteLine("Done");
                    }
                    catch (Exception ex)
                    {
                        Log.WriteLine(ex.Message);
                    }
                    Log.WriteMajorSeparatorLine();
                }
            }
        }

        private void deleteUserToolStripMenuItem_Click(object sender, EventArgs e)
        {
            using (ParameterSettingsForm form = new ParameterSettingsForm(SettingsMode.User))
            {
                if (form.ShowDialog() == DialogResult.OK)
                {
                    Guid guid = form.guid;
                    Log.WriteMajorSeparatorLine();
                    Log.WriteLine("DeleteUser " + guid.ToString() + ":");
                    SecurityServiceClient proxy = new SecurityServiceClient();
                    try
                    {
                        proxy.DeleteUser(guid);
                        Log.WriteLine("Done");
                    }
                    catch (Exception ex)
                    {
                        Log.WriteLine(ex.Message);
                    }
                    Log.WriteMajorSeparatorLine();
                }
            }
        }

        private void listGroupsOfUserToolStripMenuItem_Click(object sender, EventArgs e)
        {
            using (ParameterSettingsForm form = new ParameterSettingsForm(SettingsMode.User))
            {
                if (form.ShowDialog() == DialogResult.OK)
                {
                    Guid guid = form.guid;
                    Log.WriteMajorSeparatorLine();
                    Log.WriteLine("ListGroupsOfUser " + guid.ToString() + ":");
                    Log.WriteMinorSeparatorLine();
                    SecurityServiceClient proxy = new SecurityServiceClient();
                    try
                    {
                        GroupInfo[] groupInfos = proxy.ListGroupsOfUser(guid);
                        Log.Write(GroupInfo.CollectionToString(groupInfos));
                    }
                    catch (Exception ex)
                    {
                        Log.WriteLine(ex.Message);
                    }
                    Log.WriteMajorSeparatorLine();
                }
            }
        }

        private void setGroupsOfUserToolStripMenuItem_Click(object sender, EventArgs e)
        {
            using (ParameterSettingsForm form = new ParameterSettingsForm(SettingsMode.UserAndGroups))
            {
                if (form.ShowDialog() == DialogResult.OK)
                {
                    Guid userGuid = form.guid;
                    Guid[] groupGuids = form.guids;
                    Log.WriteMajorSeparatorLine();
                    Log.WriteLine("SetGroupsOfUser " + userGuid.ToString() + ":");
                    SecurityServiceClient proxy = new SecurityServiceClient();
                    try
                    {
                        proxy.SetGroupsOfUser(userGuid, groupGuids);
                        Log.WriteLine("Done");
                    }
                    catch (Exception ex)
                    {
                        Log.WriteLine(ex.Message);
                    }
                    Log.WriteMajorSeparatorLine();
                }
            }
        }

        #endregion

        #region GroupManagement

        private void listGroupsToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Log.WriteMajorSeparatorLine();
            Log.WriteLine("ListGroups called:");
            Log.WriteMinorSeparatorLine();
            SecurityServiceClient proxy = new SecurityServiceClient();
            try
            {
                GroupInfo[] groupInfos = proxy.ListGroups();
                Log.Write(GroupInfo.CollectionToString(groupInfos));
            }
            catch (Exception ex)
            {
                Log.WriteLine(ex.Message);
            }
            Log.WriteMajorSeparatorLine();
        }

        private void getGroupToolStripMenuItem_Click(object sender, EventArgs e)
        {
            using (ParameterSettingsForm form = new ParameterSettingsForm(SettingsMode.Group))
            {
                if (form.ShowDialog() == DialogResult.OK)
                {
                    Guid guid = form.guid;
                    Log.WriteMajorSeparatorLine();
                    Log.WriteLine("GetGroup " + guid.ToString() + ":");
                    Log.WriteMinorSeparatorLine();
                    SecurityServiceClient proxy = new SecurityServiceClient();
                    try
                    {
                        GroupInfo groupInfo = proxy.GetGroup(guid);
                        if (groupInfo != null)
                        {
                            Log.WriteLine(groupInfo.ToString());
                        }
                        else Log.WriteLine("Group guid does not exist");
                    }
                    catch (Exception ex)
                    {
                        Log.WriteLine(ex.Message);
                    }
                    Log.WriteMajorSeparatorLine();
                }
            }
        }

        private void createGroupToolStripMenuItem_Click(object sender, EventArgs e)
        {
            using (NameSettingForm form = new NameSettingForm(NameSettingMode.Group))
            {
                if (form.ShowDialog() == DialogResult.OK)
                {
                    string name = form.name;
                    Log.WriteMajorSeparatorLine();
                    Log.WriteLine("CreateGroup called:");
                    GroupInfo groupInfo = new GroupInfo(Guid.NewGuid(), name, "", false);
                    SecurityServiceClient proxy = new SecurityServiceClient();
                    Guid guid;
                    try
                    {
                        guid = proxy.CreateGroup(groupInfo);
                        Log.WriteLine("The guid of the newly created group is: " + guid.ToString());

                    }
                    catch (Exception ex)
                    {
                        Log.WriteLine(ex.Message);
                    }
                    Log.WriteMajorSeparatorLine();
                }
            }
        }

        private void updateGroupToolStripMenuItem_Click(object sender, EventArgs e)
        {
            using (ParameterSettingsForm form = new ParameterSettingsForm(SettingsMode.Group))
            {
                if (form.ShowDialog() == DialogResult.OK)
                {
                    Guid guid = form.guid;
                    Log.WriteMajorSeparatorLine();
                    Log.WriteLine("UpdateGroup " + guid.ToString() + ":");
                    SecurityServiceClient proxy = new SecurityServiceClient();
                    try
                    {
                        GroupInfo groupInfo = proxy.GetGroup(guid);
                        groupInfo.Description = groupInfo.Description + "_U";
                        groupInfo.GroupName = groupInfo.GroupName + "_U";
                        groupInfo.IsDisabled = !groupInfo.IsDisabled;
                        proxy.UpdateGroup(groupInfo);
                        Log.WriteLine("Done");
                    }
                    catch (Exception ex)
                    {
                        Log.WriteLine(ex.Message);
                    }
                    Log.WriteMajorSeparatorLine();
                }
            }
        }

        private void deleteGroupToolStripMenuItem_Click(object sender, EventArgs e)
        {
            using (ParameterSettingsForm form = new ParameterSettingsForm(SettingsMode.User))
            {
                if (form.ShowDialog() == DialogResult.OK)
                {
                    Guid guid = form.guid;
                    Log.WriteMajorSeparatorLine();
                    Log.WriteLine("DeleteGroup " + guid.ToString() + ":");
                    SecurityServiceClient proxy = new SecurityServiceClient();
                    try
                    {
                        proxy.DeleteGroup(guid);
                        Log.WriteLine("Done");
                    }
                    catch (Exception ex)
                    {
                        Log.WriteLine(ex.Message);
                    }
                    Log.WriteMajorSeparatorLine();
                }
            }
        }

        private void listUsersOfGroupToolStripMenuItem_Click(object sender, EventArgs e)
        {
            using (ParameterSettingsForm form = new ParameterSettingsForm(SettingsMode.Group))
            {
                if (form.ShowDialog() == DialogResult.OK)
                {
                    Guid guid = form.guid;
                    Log.WriteMajorSeparatorLine();
                    Log.WriteLine("ListUsersOfGroup " + guid.ToString() + ":");
                    Log.WriteMinorSeparatorLine();
                    SecurityServiceClient proxy = new SecurityServiceClient();
                    try
                    {
                        UserInfo[] userInfos = proxy.ListUsersOfGroup(guid);
                        Log.Write(UserInfo.CollectionToString(userInfos));
                        Log.WriteMajorSeparatorLine();
                    }
                    catch (Exception ex)
                    {
                        Log.WriteLine(ex.Message);
                    }
                }
            }
        }

        private void setUsersOfGroupToolStripMenuItem_Click(object sender, EventArgs e)
        {
            using (ParameterSettingsForm form = new ParameterSettingsForm(SettingsMode.GroupAndUsers))
            {
                if (form.ShowDialog() == DialogResult.OK)
                {
                    Guid groupGuid = form.guid;
                    Guid[] userGuids = form.guids;
                    Log.WriteMajorSeparatorLine();
                    Log.WriteLine("SetUsersOfGroup " + groupGuid.ToString() + ":");
                    SecurityServiceClient proxy = new SecurityServiceClient();
                    try
                    {
                        proxy.SetUsersOfGroup(groupGuid, userGuids);
                        Log.WriteLine("Done");
                    }
                    catch (Exception ex)
                    {
                        Log.WriteLine(ex.Message);
                    }
                    Log.WriteMajorSeparatorLine();
                }
            }
        }

        #endregion

        private void securityLogin(string username, string password)
        {
            Log.WriteMajorSeparatorLine();
            Log.WriteLine("Loggin in to server...");
            using (var proxy = new SecurityServiceClient())
            {
                const string memoqPasswordHashSalt = "fgad s d f sgds g  sdg gfdg";
                string passwordHash = System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(password + memoqPasswordHashSalt, "sha1");
                currentSessionId = proxy.Login(username, passwordHash);
                Log.WriteLine("Login succesful.");
            }
            Log.WriteMajorSeparatorLine();
        }

        private void securityLogout()
        {
            Log.WriteMajorSeparatorLine();
            Log.WriteLine("Loging out from server...");
            using (var proxy = new SecurityServiceClient())
            {
                proxy.Logout(currentSessionId);
                currentSessionId = null;
                Log.WriteLine("Logout succesful.");
            }
            Log.WriteMajorSeparatorLine();
        }

        #region security event handlers

        private void loginToolStripMenuItem_Click(object sender, EventArgs e)
        {
            try
            {
                using (var f = new Security.LoginForm())
                {
                    if (f.ShowDialog(this) == System.Windows.Forms.DialogResult.OK)
                        securityLogin(f.Username, f.Password);
                }
            }
            catch (FaultException ex)
            {
                if (ex.Code.Name == "Server.Expected")
                    MessageBox.Show("Expected exception. The following message can be displayed to the user: \n\n" +
                        ex.Message);
                else
                {
                    MessageBox.Show("Unexpected exception. See server log for details.");
                }
            }
        }

        private void logoutToolStripMenuItem_Click(object sender, EventArgs e)
        {
            try
            {
                securityLogout();
            }
            catch (FaultException ex)
            {
                if (ex.Code.Name == "Server.Expected")
                    MessageBox.Show("Expected exception. The following message can be displayed to the user: \n\n" +
                        ex.Message);
                else
                {
                    MessageBox.Show("Unexpected exception. See server log for details.");
                }
            }
        }

        #endregion

        #endregion

        #region TB services

        private void tbCreateAndPublish()
        {
            Log.WriteMajorSeparatorLine();
            Log.WriteLine("Create TB called:");
            TBInfo tbInfo = new TBInfo(Guid.Empty, "testTBName - " + DateTime.Now.ToString("yyyyMMdd_hhmmss"), "testDesc", false,
                new string[] { "eng", "hun" });

            TBServiceClient proxy = new TBServiceClient();
            Guid guid = proxy.CreateAndPublish(tbInfo);
            Log.WriteLine("The guid of the newly created TB is: " + guid.ToString());
            Log.WriteMajorSeparatorLine();
        }

        private void tbCloneTB()
        {
            Log.WriteMajorSeparatorLine();
            Log.WriteLine("Clone TB called:");
            TBInfo tbInfo = new TBInfo(Guid.Empty, "testTBName - " + DateTime.Now.ToString("yyyyMMdd_hhmmss"), "testDesc", false,
                new string[] { "eng", "hun" });

            using (TBServiceClient proxy = new TBServiceClient())
            {
                Guid guid = proxy.CreateAndPublish(tbInfo);
                string tbName = "testClonedTBName - " + DateTime.Now.ToString("yyyyMMdd_hhmmss");
                TBCloneInfo cloneInfo = new TBCloneInfo
                {
                    SourceTBGuid = guid,
                    TargetTBName = tbName
                };
                Guid clonedGuid = proxy.CloneTB(cloneInfo);
                TBInfo originalTB = proxy.GetTBInfo(guid);
                TBInfo clonedTB = proxy.GetTBInfo(clonedGuid);

                Log.WriteLine("Original TB info: ");
                Log.WriteLine("Guid: " + originalTB.Guid);
                Log.WriteLine("Name: " + originalTB.Name);
                Log.WriteLine("IsQTerm: " + originalTB.IsQTerm);
                Log.WriteLine("LanguageCodes: " + string.Join(",", originalTB.LanguageCodes));
                Log.WriteLine("Description: " + originalTB.Description);

                Log.WriteLine("");
                Log.WriteLine("Cloned TB info: ");
                Log.WriteLine("Guid: " + clonedTB.Guid);
                Log.WriteLine("Name: " + clonedTB.Name);
                Log.WriteLine("IsQTerm: " + clonedTB.IsQTerm);
                Log.WriteLine("LanguageCodes: " + string.Join(",", originalTB.LanguageCodes));
                Log.WriteLine("Description: " + clonedTB.Description);

                proxy.DeleteTB(guid);
                proxy.DeleteTB(clonedGuid);
            }

            Log.WriteMajorSeparatorLine();
        }

        private void tbList(bool filerByLanguages)
        {
            string[] languages = null;

            Log.WriteMajorSeparatorLine();
            if (filerByLanguages)
            {
                using (LanguageSettingForm form = new LanguageSettingForm())
                {
                    if (form.ShowDialog() == DialogResult.OK)
                    {
                        languages = form.Languages;
                        string langToString = "";
                        foreach (string s in languages)
                            langToString += s + ", ";

                        Log.WriteLine("List TBs filtered (" + langToString + "):");
                    }
                }
            }
            else
                Log.WriteLine("List TBs:");
            Log.WriteMinorSeparatorLine();

            try
            {
                TBServiceClient proxy = new TBServiceClient();
                TBInfo[] tbs = proxy.ListTBs(languages);
                Log.Write(TBInfo.CollectionToString(tbs));
            }
            catch (Exception ex)
            {
                Log.WriteLine(ex.Message);
            }
            Log.WriteMajorSeparatorLine();
        }

        private void tbExportCSV(int p)
        {
            Log.WriteMajorSeparatorLine();
            Log.WriteLine("Exporting TB #" + ((int)(p + 1)).ToString() + " to CSV:");
            TBServiceClient proxy = new TBServiceClient();
            TBInfo[] tbInfos = proxy.ListTBs(null);
            if (p >= tbInfos.Length)
            {
                Log.WriteLine("Error. No TB exist in the list at this position.");
                Log.WriteMajorSeparatorLine();
                return;
            }
            using (SaveFileDialog sfd = new SaveFileDialog())
            {
                sfd.OverwritePrompt = true;
                sfd.Filter = "CSV file|*.csv";
                sfd.DefaultExt = ".csv";
                if (sfd.ShowDialog() == DialogResult.OK)
                {
                    string filename = sfd.FileName;
                    Log.WriteLine("Exporting to: " + filename);
                    DateTime begin = DateTime.Now;
                    Guid sessionId = proxy.BeginChunkedCSVExport(tbInfos[p].Guid);
                    try
                    {
                        using (System.IO.FileStream fs = System.IO.File.Create(filename))
                        {
                            System.IO.BinaryWriter bw = new System.IO.BinaryWriter(fs);
                            byte[] buffer;
                            while ((buffer = proxy.GetNextExportChunk(sessionId)) != null)
                                bw.Write(buffer);
                            bw.Flush();
                            bw.Close();
                        }
                    }
                    finally
                    {
                        proxy.EndChunkedExport(sessionId);
                    }
                    DateTime end = DateTime.Now;
                    Log.WriteLine(string.Format("Duration: {0} sec", ((TimeSpan)(end - begin)).TotalSeconds));
                    Log.WriteLine("Done.");
                }
                else
                    Log.WriteLine("cancelled");
                Log.WriteMajorSeparatorLine();
            }
        }

        private void tbExportMultiTerm(int p)
        {
            Log.WriteMajorSeparatorLine();
            Log.WriteLine("Exporting TB #" + ((int)(p + 1)).ToString() + " to MultiTerm:");
            TBServiceClient proxy = new TBServiceClient();
            TBInfo[] tbInfos = proxy.ListTBs(null);
            if (p >= tbInfos.Length)
            {
                Log.WriteLine("Error. No TB exist in the list at this position.");
                Log.WriteMajorSeparatorLine();
                return;
            }
            using (SaveFileDialog sfd = new SaveFileDialog())
            {
                sfd.OverwritePrompt = true;
                sfd.Filter = "MultiTerm XML file|*.xml";
                sfd.DefaultExt = ".xml";
                if (sfd.ShowDialog() == DialogResult.OK)
                {
                    string filename = sfd.FileName;
                    Log.WriteLine("Exporting to: " + filename);
                    string xdl, xdt;
                    DateTime begin = DateTime.Now;
                    Guid sessionId = proxy.BeginChunkedMultiTermExport(out xdt, out xdl, tbInfos[p].Guid);
                    using (StreamWriter sw = new StreamWriter(System.IO.Path.ChangeExtension(filename, ".xdl")))
                    {
                        sw.Write(xdl);
                    }
                    using (StreamWriter sw = new StreamWriter(System.IO.Path.ChangeExtension(filename, ".xdt")))
                    {
                        sw.Write(xdt);
                    }
                    try
                    {
                        using (System.IO.FileStream fs = System.IO.File.Create(filename))
                        {
                            System.IO.BinaryWriter bw = new System.IO.BinaryWriter(fs);
                            byte[] buffer;
                            while ((buffer = proxy.GetNextExportChunk(sessionId)) != null)
                                bw.Write(buffer);
                            bw.Flush();
                            bw.Close();
                        }
                    }
                    finally
                    {
                        proxy.EndChunkedExport(sessionId);
                    }
                    DateTime end = DateTime.Now;
                    Log.WriteLine(string.Format("Duration: {0} sec", ((TimeSpan)(end - begin)).TotalSeconds));
                    Log.WriteLine("Done.");
                }
                else
                    Log.WriteLine("cancelled");
                Log.WriteMajorSeparatorLine();
            }
        }

        private Guid tbImportCSV(int p)
        {
            Log.WriteMajorSeparatorLine();
            Log.WriteLine("Importing CSV into TB #" + ((int)(p + 1)).ToString() + ":");
            TBServiceClient proxy = new TBServiceClient();
            TBInfo[] tbInfos = proxy.ListTBs(null);
            if (p >= tbInfos.Length)
            {
                Log.WriteLine("Error. No TB exist in the list at this position.");
                Log.WriteMajorSeparatorLine();
                return Guid.Empty;
            }
            using (OpenFileDialog ofd = new OpenFileDialog())
            {
                ofd.CheckFileExists = true;
                ofd.Filter = "CSV file|*.csv";
                if (ofd.ShowDialog() == DialogResult.OK)
                {
                    string filename = ofd.FileName;
                    Log.WriteLine("Importing from: " + filename);
                    DateTime begin = DateTime.Now;
                    Guid sessionId = proxy.BeginChunkedCSVImport(tbInfos[p].Guid, null);
                    using (System.IO.StreamReader sr = new System.IO.StreamReader(filename, true))
                    {
                        char[] buffer = new char[50000];
                        byte[] bbuffer;
                        while (true)
                        {
                            int readCharsCount = sr.Read(buffer, 0, 50000);
                            if (readCharsCount == 0)
                                break;
                            bbuffer = Encoding.GetEncoding("UTF-16").GetBytes(buffer, 0, readCharsCount);
                            proxy.AddNextCSVChunk(sessionId, bbuffer);
                        }
                        sr.Close();
                    }
                    CSVImportResult res = proxy.EndChunkedCSVImport(sessionId);
                    DateTime end = DateTime.Now;
                    Log.WriteLine(string.Format("successfully imported {0} entries of {1}.", res.SuccessCount, res.AllCount));
                    Log.WriteLine(string.Format("Duration: {0} sec", ((TimeSpan)(end - begin)).TotalSeconds));
                    Log.WriteLine("Done.");
                    return tbInfos[0].Guid;
                }
                else
                    Log.WriteLine("cancelled");
                Log.WriteMajorSeparatorLine();
                return Guid.Empty;
            }
        }

        private void tbDelete(int p)
        {
            Log.WriteMajorSeparatorLine();
            Log.WriteLine("Delete TB #" + ((int)(p + 1)).ToString() + ":");
            TBServiceClient proxy = new TBServiceClient();
            TBInfo[] tbInfos = proxy.ListTBs(null);
            if (p >= tbInfos.Length)
            {
                Log.WriteLine("Error. No TB exist in the list at this position.");
                Log.WriteMajorSeparatorLine();
                return;
            }
            proxy.DeleteTB(tbInfos[p].Guid);
            Log.WriteLine("Done.");
            Log.WriteMajorSeparatorLine();
        }

        #region TB related menuitem event handlers

        private void tbCreateAndPublishToolStripMenuItem_Click(object sender, EventArgs e)
        {
            try
            {
                tbCreateAndPublish();

            }
            catch (FaultException ex)
            {
                if (ex.Code.Name == "Server.Expected")
                    MessageBox.Show("Expected exception. The following message can be displayed to the user: \n\n" +
                        ex.Message);
                else
                    MessageBox.Show("Unexpected exception. See MemoQ server log for details.\nMessage: "
                        + ex.Message);
            }
        }

        private void cloneTBToolStripMenuItem_Click(object sender, EventArgs e)
        {
            try
            {
                tbCloneTB();
            }
            catch (FaultException ex)
            {
                if (ex.Code.Name == "Server.Expected")
                    MessageBox.Show("Expected exception. The following message can be displayed to the user: \n\n" +
                        ex.Message);
                else
                {
                    MessageBox.Show("Unexpected exception. See server log for details.");
                }
            }
        }

        private void tbListTBs_Click(object sender, EventArgs e)
        {
            try
            {
                tbList(false);

            }
            catch (FaultException ex)
            {
                if (ex.Code.Name == "Server.Expected")
                    MessageBox.Show("Expected exception. The following message can be displayed to the user: \n\n" +
                        ex.Message);
                else
                    MessageBox.Show("Unexpected exception. See MemoQ server log for details.\nMessage: "
                        + ex.Message);
            }
        }

        private void exportTB1ToCSVToolStripMenuItem_Click(object sender, EventArgs e)
        {
            try
            {
                tbExportCSV(0);

            }
            catch (FaultException ex)
            {
                if (ex.Code.Name == "Server.Expected")
                    MessageBox.Show("Expected exception. The following message can be displayed to the user: \n\n" +
                        ex.Message);
                else
                    MessageBox.Show("Unexpected exception. See MemoQ server log for details.\nMessage: "
                        + ex.Message);
            }
        }

        private void exportTB2ToCSVToolStripMenuItem_Click(object sender, EventArgs e)
        {
            try
            {
                tbExportCSV(1);

            }
            catch (FaultException ex)
            {
                if (ex.Code.Name == "Server.Expected")
                    MessageBox.Show("Expected exception. The following message can be displayed to the user: \n\n" +
                        ex.Message);
                else
                    MessageBox.Show("Unexpected exception. See MemoQ server log for details.\nMessage: "
                        + ex.Message);
            }
        }

        private void exportTB3ToCSVToolStripMenuItem_Click(object sender, EventArgs e)
        {
            try
            {
                tbExportCSV(2);

            }
            catch (FaultException ex)
            {
                if (ex.Code.Name == "Server.Expected")
                    MessageBox.Show("Expected exception. The following message can be displayed to the user: \n\n" +
                        ex.Message);
                else
                    MessageBox.Show("Unexpected exception. See MemoQ server log for details.\nMessage: "
                        + ex.Message);
            }
        }

        private void tbImportCSVIntoTB1ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            try
            {
                var guid = tbImportCSV(0);
            }
            catch (FaultException ex)
            {
                if (ex.Code.Name == "Server.Expected")
                    MessageBox.Show("Expected exception. The following message can be displayed to the user: \n\n" +
                        ex.Message);
                else
                    MessageBox.Show("Unexpected exception. See MemoQ server log for details.\nMessage: "
                        + ex.Message);
            }
        }

        private void tbImportCSVIntoTB2ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            try
            {
                tbImportCSV(1);

            }
            catch (FaultException ex)
            {
                if (ex.Code.Name == "Server.Expected")
                    MessageBox.Show("Expected exception. The following message can be displayed to the user: \n\n" +
                        ex.Message);
                else
                    MessageBox.Show("Unexpected exception. See MemoQ server log for details.\nMessage: "
                        + ex.Message);
            }
        }

        private void tbImportCSVIntoTB2ToolStripMenuItem1_Click(object sender, EventArgs e)
        {
            try
            {
                tbImportCSV(2);

            }
            catch (FaultException ex)
            {
                if (ex.Code.Name == "Server.Expected")
                    MessageBox.Show("Expected exception. The following message can be displayed to the user: \n\n" +
                        ex.Message);
                else
                    MessageBox.Show("Unexpected exception. See MemoQ server log for details.\nMessage: "
                        + ex.Message);
            }
        }

        private void tbDeleteTB1ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            try
            {
                tbDelete(0);

            }
            catch (FaultException ex)
            {
                if (ex.Code.Name == "Server.Expected")
                    MessageBox.Show("Expected exception. The following message can be displayed to the user: \n\n" +
                        ex.Message);
                else
                    MessageBox.Show("Unexpected exception. See MemoQ server log for details.\nMessage: "
                        + ex.Message);
            }
        }

        private void tbDeleteTB2ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            try
            {
                tbDelete(1);

            }
            catch (FaultException ex)
            {
                if (ex.Code.Name == "Server.Expected")
                    MessageBox.Show("Expected exception. The following message can be displayed to the user: \n\n" +
                        ex.Message);
                else
                    MessageBox.Show("Unexpected exception. See MemoQ server log for details.\nMessage: "
                        + ex.Message);
            }
        }

        private void tbDeleteTB3ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            try
            {
                tbDelete(2);

            }
            catch (FaultException ex)
            {
                if (ex.Code.Name == "Server.Expected")
                    MessageBox.Show("Expected exception. The following message can be displayed to the user: \n\n" +
                        ex.Message);
                else
                    MessageBox.Show("Unexpected exception. See MemoQ server log for details.\nMessage: "
                        + ex.Message);
            }
        }

        private void listTBsFilteredToolStripMenuItem_Click(object sender, EventArgs e)
        {
            try
            {
                tbList(true);

            }
            catch (FaultException ex)
            {
                if (ex.Code.Name == "Server.Expected")
                    MessageBox.Show("Expected exception. The following message can be displayed to the user: \n\n" +
                        ex.Message);
                else
                    MessageBox.Show("Unexpected exception. See MemoQ server log for details.\nMessage: "
                        + ex.Message);
            }
        }

        private void exportTB1ToMultiTermToolStripMenuItem_Click(object sender, EventArgs e)
        {
            try
            {
                tbExportMultiTerm(0);

            }
            catch (FaultException ex)
            {
                if (ex.Code.Name == "Server.Expected")
                    MessageBox.Show("Expected exception. The following message can be displayed to the user: \n\n" +
                        ex.Message);
                else
                    MessageBox.Show("Unexpected exception. See MemoQ server log for details.\nMessage: "
                        + ex.Message);
            }
        }

        private void exportTB1ToMultiTermToolStripMenuItem1_Click(object sender, EventArgs e)
        {
            try
            {
                tbExportMultiTerm(1);

            }
            catch (FaultException ex)
            {
                if (ex.Code.Name == "Server.Expected")
                    MessageBox.Show("Expected exception. The following message can be displayed to the user: \n\n" +
                        ex.Message);
                else
                    MessageBox.Show("Unexpected exception. See MemoQ server log for details.\nMessage: "
                        + ex.Message);
            }
        }

        private void exportTB3ToMultiTermToolStripMenuItem_Click(object sender, EventArgs e)
        {
            try
            {
                tbExportMultiTerm(2);

            }
            catch (FaultException ex)
            {
                if (ex.Code.Name == "Server.Expected")
                    MessageBox.Show("Expected exception. The following message can be displayed to the user: \n\n" +
                        ex.Message);
                else
                    MessageBox.Show("Unexpected exception. See MemoQ server log for details.\nMessage: "
                        + ex.Message);
            }
        }

        #endregion

        #endregion

        #region PermissionManagement

        private void setObjectPermissionsToolStripMenuItem_Click(object sender, EventArgs e)
        {
            using (ParameterSettingsForm form = new ParameterSettingsForm(SettingsMode.ObjectAndUsers))
            {
                if (form.ShowDialog() == DialogResult.OK)
                {
                    Guid guid = form.guid;
                    Guid[] guids = form.guids;
                    ObjectPermission[] permissions = new ObjectPermission[guids.Length];
                    for (int i = 0; i < guids.Length; i++)
                    {
                        permissions[i] = new ObjectPermission(guids[i], 1, new DateTime(2500, 1, 1));
                    }
                    Log.WriteMajorSeparatorLine();
                    Log.WriteLine("SetObjectPermissions " + guid.ToString() + ":");
                    SecurityServiceClient proxy = new SecurityServiceClient();
                    try
                    {
                        proxy.SetObjectPermissions(guid, permissions);
                        Log.WriteLine("Done");
                    }
                    catch (Exception ex)
                    {
                        Log.WriteLine(ex.Message);
                    }
                    Log.WriteMajorSeparatorLine();
                }
            }
        }

        private void listObjectPermissionsToolStripMenuItem_Click(object sender, EventArgs e)
        {
            using (ParameterSettingsForm form = new ParameterSettingsForm(SettingsMode.Object))
            {
                if (form.ShowDialog() == DialogResult.OK)
                {
                    Guid guid = form.guid;
                    Log.WriteMajorSeparatorLine();
                    Log.WriteLine("ListObjectPermissions " + guid.ToString() + ":");
                    Log.WriteMinorSeparatorLine();
                    SecurityServiceClient proxy = new SecurityServiceClient();
                    try
                    {
                        ObjectPermission[] permissions = proxy.ListObjectPermissions(guid);
                        Log.Write(ObjectPermission.CollectionToString(permissions));
                    }
                    catch (Exception ex)
                    {
                        Log.WriteLine(ex.Message);
                    }
                    Log.WriteMajorSeparatorLine();
                }
            }
        }

        #endregion

        private void fullTestImportExportToolStripMenuItem_Click(object sender, EventArgs e)
        {
            ServerProjectServiceTest test = new ServerProjectServiceTest();
            Stopwatch sw = new Stopwatch();
            sw.Start();
            string spName = test.DemoTest();
            sw.Stop();
            string s = string.Format("Server project has been imported. Name: {0}\r\nTime elapsed: {1}",
                spName, sw.Elapsed);
            MessageBox.Show(s);
        }

        private void testAPIKeyToolStripMenuItem_Click(object sender, EventArgs e)
        {
            TestApiKeyForm form = new TestApiKeyForm();
            form.ShowDialog();
        }


        private void runStatisticsAsyncToolStripMenuItem_Click(object sender, EventArgs e)
        {
            ServerProjectServiceTest test = new ServerProjectServiceTest();
            Stopwatch sw = new Stopwatch();
            sw.Start();
            try
            {
                string spName = test.StatisticsAsyncTest();
                sw.Stop();
                string s = string.Format("Statistics finished successfully. File imported: {0}\r\nTime elapsed: {1}",
                    spName, sw.Elapsed);
                MessageBox.Show(s);
            }
            catch(Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void createQTermTBFromMultTtermZIPToolStripMenuItem_Click(object sender, EventArgs e)
        {
            using (var optionsForm = new CreateQTermFromMultitermForm())
            {
                if (!(optionsForm.ShowDialog() == DialogResult.OK))
                    return;

                try
                {
                    Log.WriteLine("Fileupload in progress...");
                    var guid = FileManager.UploadFile(new FileManagerService.FileManagerServiceClient("FileManagerService"), optionsForm.FilePath);
                    Log.WriteLine("Fileupload finished successfuly");

                    TBServiceClient proxy = new TBServiceClient();
                    var tbInfo = new TBInfo(Guid.NewGuid(), optionsForm.QTermName, "", false, null);
                    var importSettings = new QTermTBImportSettings();
                    importSettings.MultitermZipFileId = guid;

                    Log.WriteLine("CreateQTermTBFromMultiterm in progress...");
                    var tbGuid = proxy.CreateQTermTBFromMultiterm(tbInfo, importSettings);
                    Log.WriteLine($"CreateQTermTBFromMultiterm finished successfuly; QTerm with guid: {tbGuid} created");
                }
                catch (Exception ex)
                {
                    Log.WriteLine("CreateQTermTBFromMultiterm failed:");
                    Log.WriteLine(ex.Message);
                }
            }
        }
    }
}
