using System;
using System.IO;
using System.Runtime.Serialization;
using System.Xml;
using Digst.OioIdws.OioWsTrust;
using Digst.OioIdws.Wsc.OioWsTrust;
using SEI2.TestConsole.Bundles;
using SEI2.TestConsole.SEI2ReportProxy;

namespace SEI2.TestConsole
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.OutputEncoding = Console.InputEncoding = System.Text.Encoding.GetEncoding("windows-1252");
            Console.WriteLine("Enter filepath to send it (or type 'exit' or 'q'): ");
            Console.WriteLine("");
            Console.WriteLine("For Bundle examples type 'Bundle x':");
            Console.WriteLine("- 'Bundle 1': Import without server-side sorting.");
            Console.WriteLine("- 'Bundle 2': Import with server-side sorting.");
            Console.WriteLine("- 'Bundle 3': The bundle has an error.");
            Console.WriteLine("- 'Bundle 4': One of the entries has an error. ");
            Console.WriteLine("- 'Bundle 5': Cancel and Update.");
            Console.WriteLine("- 'Bundle 6': Get user details.");

            while (true)
            {
                string userInput = Console.ReadLine();
                if (userInput == "exit" || userInput == "q")
                {
                    break;
                }

                if (userInput.ToLower().StartsWith("bundle"))
                    BundleExample.Call(userInput);
                else if (File.Exists(userInput))
                    Submit(userInput);
                else
                    Console.WriteLine("File does not exist.");
            }
        }

        private static void Submit(string filePath)
        {
            try
            {
                var contract = FactoryContract.CreateContractOrException(filePath);
                var invokeService = FactoryService.CreateServiceActionOrException(filePath);

                IStsTokenService stsTokenService = new StsTokenServiceCache(TokenServiceConfigurationFactory.CreateConfiguration());
                var securityToken = stsTokenService.GetToken();

                using (var client = new SEI2ReportClient("SoapBinding_ISEI2Report"))
                {
                    var channelWithIssuedToken = client.ChannelFactory.CreateChannelWithIssuedToken(securityToken);
                    invokeService.Invoke(channelWithIssuedToken, contract);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("Unexpected error: " + ex.Message);
            }
        }
    }
}