using qtc_net_client_2.ClientModel;
using QtCNETAPI.Services.ApiService;
using QtCNETAPI.Services.GatewayService;
using System.Text.Json;
using System.Threading.Tasks;

namespace qtc_net_client_2
{
    internal static class Program
    {
        /// <summary>
        ///  The main entry point for the application.
        /// </summary>
        [STAThread]
        static async Task Main()
        {
            Config clientConfig = new Config();

            // find config file
            if(!File.Exists("./config.json"))
            {
                // create it using default config model
                string configJson = JsonSerializer.Serialize(clientConfig, options: new JsonSerializerOptions { WriteIndented = true });
                File.WriteAllText("./config.json", configJson);
            } else
            {
                // use config in file
                Config? fileConfig = JsonSerializer.Deserialize<Config>(File.ReadAllText("./config.json"));
                if(fileConfig != null)
                    clientConfig = fileConfig;
            }

            // instantiate new ApiService and GatewayService for this session
            // this will keep the gateway thread in the main thread (i think)
            IApiService api = new ApiService(clientConfig.ApiEndpoint);
            IGatewayService gateway = new GatewayService(clientConfig.GatewayEndpoint, api);

            // ping api
            var pingResult = api.PingServerAsync().GetAwaiter().GetResult();
            if (!pingResult.Success)
            {
                MessageBox.Show("The API Specified In The Config Could Not Be Reached.\nCheck The URL Specified, Otherwise Contact The Server Admin.", "Uh Oh.", MessageBoxButtons.OK, MessageBoxIcon.Error);
                Environment.Exit(1);
            }

            // To customize application configuration such as set high DPI settings or default font,
            // see https://aka.ms/applicationconfiguration.
            ApplicationConfiguration.Initialize();
            Application.Run(new Main(api, gateway));

            // if application loop is exited, dispose everything
            await gateway.DisposeAsync();

            api = null;
            gateway = null;

            Environment.Exit(0);
        }
    }
}