using Microsoft.AspNetCore.Hosting;
using System.Runtime.InteropServices;
using ServiceCenter.Extensions;
using ServiceCenter.Redis;
using ServiceCenter.WebApi;

namespace WCS.Service
{
    public class Program
    {
        public static void Main(string[] args)
        {
            #region 接入Redis

            RedisHub.CreateContext(AppSettings.Config.GetConnectionString("Redis"), "default", true);

            #endregion 接入Redis

            //互斥锁检测
            var mutexName = RedisHub.Default.Check("Mutex") ?? throw new Exception("请在Redis中配置互斥量值");

            //using var mt = new Mutex(true, mutexName);
            //if (mt.WaitOne())
            //{
                CreateHostBuilder(args).Build().Run(); /*mt.ReleaseMutex();*/
            //}
            //else
            //{
            //    Console.WriteLine("请勿重复运行");
            //    //InfoLog.INFO_INIT("请勿重复运行");
            //    Task.Delay(2000).Wait();
            //}
        }

        /// <summary>
        /// 创建一个主机构建器
        /// </summary>
        /// <param name="args"></param>
        /// <returns></returns>
        public static IHostBuilder CreateHostBuilder(string[] args)
        {
            //是否是win平台
            var isWin = RuntimeInformation.IsOSPlatform(OSPlatform.Windows);
            Console.WriteLine($"win:{isWin}");
            if (isWin)
            {
                var useUrls = RedisHub.Default.Check("UseUrls") ?? throw new Exception("请在Redis中配置网络访问端口");
                //"http://*:8080"
                return Host.CreateDefaultBuilder(args)
                    .UseWindowsService()//win
                    .ConfigureWebHostDefaults(web => //网络访问配置
                    {
                        web.UseUrls(useUrls); //设备访问端口
                        web.UseStartup<Startup>(); //调用启动服务
                    })
                    .ConfigureServices((_, services) =>
                    {
                        services.AddHostedService<Worker>();
                        services.AddHttpClient();
                    });
            }
            return Host.CreateDefaultBuilder(args)
                .UseSystemd()//linux
                .ConfigureServices((_, services) =>
                {
                    services.AddHostedService<Worker>();
                });
        }
    }
}
