using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Windows.Forms;
using System.Diagnostics;
using System.Runtime.InteropServices;

using C4IT.Security;
using C4IT.Logging;
using C4IT.DataHistoryProvider;
using C4IT.FASD.Security;
using C4IT.FASD.Licensing;
using System.Reflection;
using static C4IT.Logging.cLogManager;
using System.IO;

namespace C4IT_DataHistoryProvider_Test
{   
    static class Program
    {
        public static frmMain2 mainForm;
        public static cDataHistoryCollector Collector = null;
        public static List<cDataHistoryInfoClassListEntry> UserList = null;
        static public Mutex AppMutex = null;

        [STAThread]
        static void Main(string[] args)
        {
            // initialize the logging
            var LM = cLogManagerFile.Create(true, SubFolder: "Logs", DebugFlags: new List<string>() { "Performance", "ApiTiming" });
            cLogManager.DefaultLogger = LM.GetLogger();
            cLogManager.Instance = LM;
            cLogManager.DefaultLogger.LogAssemblyInfo();

            if (LM.CheckDebugFlag("Performance"))
            {
                var FN = LM.GetLogFileName();
                var FN2 = Path.Combine(Path.GetDirectoryName(FN), Path.GetFileNameWithoutExtension(FN) + "-Perf.log");
                cPerformanceLogger.SetManager(cLogManagerFile.Create(FN2));
            }

            DataHistorySqlHelper.LogSql = LM.CheckDebugFlag("ApiTiming");
            if (DataHistorySqlHelper.LogSql)
                DataHistorySqlHelper.SqlLogFileName = DataHistorySqlHelper.GetSqlLogFileName();

            // initialize the password securitiy
            FasdSecurity.Init();


            // check this program is already started
            Assembly assembly = Assembly.GetExecutingAssembly();
            var ProductName = FileVersionInfo.GetVersionInfo(assembly.Location).ProductName;
            var attribute = (GuidAttribute)assembly.GetCustomAttributes(typeof(GuidAttribute), true)[0];
            var AssemblyGuid = attribute.Value;
            string MutexName = "Global\\" + ProductName + AssemblyGuid.ToString();
            try
            {
                AppMutex = new Mutex(false, MutexName);
                if (!AppMutex.WaitOne(0))
                {
                    LogEntry("Application already started, exiting...", LogLevels.Info);
                    AppMutex.Dispose();
                    AppMutex = null;
                    return;
                }
            }
            catch (Exception E)
            {
                LogEntry("Cannot create application mutex, exiting...", LogLevels.Fatal);
                LogException(E);
                return;
            }



            // get the commandline command
            string Command = "";
            if ((args.Length > 0))
                Command = args[0].ToUpper();
            if (Command.StartsWith("/") || Command.StartsWith("-"))
                Command = Command.Remove(0, 1);


            // get the license file
#if DEMOLICENSE
            var strLicPath = cF4SDLicense.GetProgramFolderLocation(Assembly.GetExecutingAssembly(), "..", "F4SD_License.xml");
            cF4SDLicense.Instance.LoadFromFile(strLicPath, false);
            if (!cF4SDLicense.Instance.IsValid)
            {
                cLogManager.DefaultLogger.LogEntry(LogLevels.Fatal, $"No valid license found, aborting...");
                return;
            }
#endif

            // start the application
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);

            switch (Command)
            {
                case "PASSWORD":
                    Application.Run(new frmPassword());
                    break;
                default:
                    mainForm = new frmMain2(Command == "COLLECT");
                    Application.Run(mainForm);
                    break;
            }
        }
    }
}
