using MemoQServicesClient.SecurityService;
using MemoQServicesClient.WCF;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.ServiceModel;
using System.Text;
using System.Windows.Forms;

namespace MemoQServicesClient
{
    public partial class TestApiKeyForm : Form
    {
        public TestApiKeyForm()
        {
            InitializeComponent();
        }

        private void cbUseApiKey_CheckedChanged(object sender, EventArgs e)
        {
            tbApiKey.Enabled = cbUseApiKey.Checked;
        }

        private void btnGetUsers_Click(object sender, EventArgs e)
        {
            rtbLog.Text += Environment.NewLine;
            rtbLog.Text += "ListUsers called:";
            rtbLog.Text += Environment.NewLine;
            SecurityServiceClient proxy = new SecurityServiceClient();
            // use the content of textbox as API key
            if (cbUseApiKey.Checked)
            {
                proxy.Endpoint.Behaviors.Add(new MemoQServicesClientBehavior());
                WsApiKeyConfig.ApiKeyHeaderValue = tbApiKey.Text;
            }

            try
            {
                UserInfo[] userInfos = proxy.ListUsers();
                rtbLog.Text += UserInfo.CollectionToString(userInfos);
            }
            catch (FaultException<GenericFault> genericFault)
            {
                if (genericFault.Detail.ErrorCode == "Generic.MissingApiKey")
                {
                    rtbLog.Text += "No API key was sent to the server";
                }
                else if (genericFault.Detail.ErrorCode == "Generic.InvalidApiKey")
                {
                    rtbLog.Text += "Invalid API key was sent to the server";
                }
                else
                {
                    rtbLog.Text += genericFault.Message;
                }
            }
            catch (Exception ex)
            {
                rtbLog.Text += ex.Message;
            }
            rtbLog.Text += Environment.NewLine;
        }

        private void btnClearLog_Click(object sender, EventArgs e)
        {
            rtbLog.Text = "";
        }
    }

    public static class WsApiKeyConfig
    {
        public const string ApiKeyHeaderKey = "ApiKey";
        public const string ApiKeyNamespace = "http://kilgray.com/memoqservices/2007";
        public static string ApiKeyHeaderValue;
    }
}
