using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.ServiceProcess;
using System.Text;
using System.Reflection;
using SuperSocket.Common;
using SuperSocket.SocketBase;
using SuperSocket.SocketEngine;
using SuperSocket.SocketEngine.Configuration;
using System.ServiceModel;

namespace TZONE.SocketService
{
    static partial class Program
    {
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        static void Main(string[] args)
        {
            try
            {
                if ((!Platform.IsMono && !Environment.UserInteractive)//Windows Service
                    || (Platform.IsMono && !AppDomain.CurrentDomain.FriendlyName.Equals(Path.GetFileName(Assembly.GetEntryAssembly().CodeBase))))//MonoService
                {
                    RunAsService();
                    return;
                }

                if (args != null && args.Length > 0)
                {
                    if (args[0].Equals("-i", StringComparison.OrdinalIgnoreCase))
                    {
                        SelfInstaller.InstallMe();
                        return;
                    }
                    else if (args[0].Equals("-u", StringComparison.OrdinalIgnoreCase))
                    {
                        SelfInstaller.UninstallMe();
                        return;
                    }

                    Console.WriteLine("Invalid argument!");
                    return;
                }

                RunAsConsole();
                Console.ReadKey();
            }
            catch (System.Exception ex)
            {
                RunAsConsole();
            }
        }


        static void RunAsConsole()
        {
            Console.WriteLine("{0} version: {1} Gateway ServiceEngine!", AppName(), AppVersion());
            //Console.ReadKey();
            //Console.WriteLine();

            Console.WriteLine("Initializing...");

            IBootstrap bootstrap = BootstrapFactory.CreateBootstrap();

            if (!bootstrap.Initialize())
            {
                Console.WriteLine("Failed to initialize {0} version: {1} ServiceEngine! Please check error log for more information!", AppName(), AppVersion());
                return;
            }

            Console.WriteLine("Starting...");

            var result = bootstrap.Start();

            Console.WriteLine("-------------------------------------------------------------------");

            foreach (var server in bootstrap.AppServers)
            {
                if (server.State == ServerState.Running)
                {
                    Console.ForegroundColor = ConsoleColor.Green;
                    Console.WriteLine("- {0} {1} has been started", AppName(), AppVersion());
                }
                else
                {
                    Console.ForegroundColor = ConsoleColor.Red;
                    Console.WriteLine("- {0} {1} failed to start", AppName(), AppVersion());
                }
            }

            Console.ResetColor();
            Console.WriteLine("-------------------------------------------------------------------");

            switch (result)
            {
                case (StartResult.None):
                    Console.ForegroundColor = ConsoleColor.Red;
                    Console.WriteLine("No server is configured, please check you configuration!");
                    break;

                case (StartResult.Success):
                    Console.WriteLine("The {0} version: {1} ServiceEngine has been started!", AppName(), AppVersion());
                    //读取IMEI
                    //GPSSocketServer.Common.IMEIFilter.ResetIMEIHash();
                    break;

                case (StartResult.Failed):
                    Console.ForegroundColor = ConsoleColor.Red;
                    Console.WriteLine("Failed to start the {0} version: {1} ServiceEngine! Please check error log for more information!", AppName(), AppVersion());
                    break;

                case (StartResult.PartialSuccess):
                    Console.ForegroundColor = ConsoleColor.Red;
                    Console.WriteLine("Some server instances were started successfully, but the others failed! Please check error log for more information!");
                    break;
            }
            //启动wcf
            StartTZONEContracts();
            Console.ResetColor();
            Console.WriteLine("Press key 'q' to stop the ServiceEngine.");

            while (Console.ReadKey().Key != ConsoleKey.Q)
            {
                Console.WriteLine();
                continue;
            }

            bootstrap.Stop();

            Console.WriteLine();
            Console.WriteLine("The {0} version: {1} ServiceEngine has been stopped!", AppName(), AppVersion());
        }

        static void RunAsService()
        {
            ServiceBase[] servicesToRun;

            servicesToRun = new ServiceBase[] { new MainService() };

            ServiceBase.Run(servicesToRun);
        }
        static string AppVersion()
        {
            return System.Reflection.Assembly.GetExecutingAssembly().GetName().Version.ToString();
        }
        static string AppName()
        {
            return System.Reflection.Assembly.GetExecutingAssembly().GetName().Name.ToString();
        }

        static void StartTZONEContracts()
        {
            ServiceHost tzonehost;
            tzonehost = new ServiceHost(typeof(TZONE.GPSSocketServer.Common.IMEIFilter));
            tzonehost.Opened += delegate { Console.WriteLine("Down command is started!"); };
            tzonehost.Closed += delegate { Console.WriteLine("Down command is closed!"); };
            tzonehost.Open();
        }
    }
}
