using FLY.OBJComponents.IService;
using FLY.Thick.Base.IService;
using FLY.Thick.FilmCasting.IService;
using Microsoft.Owin.Hosting;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Unity;

namespace FLY.Thick.FilmCasting.WebAPI
{
    /// <summary>
    /// 测厚仪 WebAPI 服务
    /// </summary>
    public class ThkWebApiServer : INotifyPropertyChanged
    {
        public event PropertyChangedEventHandler PropertyChanged;

        /// <summary>
        /// 服务地址
        /// </summary>
        public string ServerAddr { get; set; }= "localhost:10010";
        /// <summary>
        /// 运行中
        /// </summary>
        public bool IsRunning { get; set; }


        FLY.Thick.FilmCasting.Server.TDGage thkGage;
        IDisposable webApp=null;
        public ThkWebApiServer() 
        {
            if (!Load())
                Save();
        }

        public void Init(
            FLY.Thick.FilmCasting.Server.TDGage thkGage
            ) 
        {
            this.thkGage = thkGage;
        }
        public void Start() 
        {
            //webapp 被释放后， 容器也会清空释放。 所以不要存储容器
            Stop();

            //配置容器
            UnityContainer container = new UnityContainer();

            container.RegisterInstance((IWarningSystem2Service)thkGage.warning);
            container.RegisterInstance<IThkGaugeService>(thkGage);
            container.RegisterInstance<IBorderSearchService>(thkGage.borderSearch);
            container.RegisterInstance<ICurveService>(thkGage.curve);
            container.RegisterInstance<FLY.Thick.FilmCasting.IService.IInitParamService>(thkGage.initParam);
            container.RegisterInstance<IScanCorrService>(thkGage.gmScanCorr);

            container.RegisterInstance<IFlyADService>(thkGage.flyAdService);

            container.RegisterInstance <IFixService>(thkGage.gmFix);


            container.RegisterInstance < IFilmCastingProfileService>(thkGage.profile);

            container.RegisterInstance < IScanWarningService>(thkGage.scanWarning);

            container.RegisterInstance < IBoltMapFilmCastingService>(thkGage.boltmap);

            container.RegisterInstance < IRejectService>(thkGage.reject);

            container.RegisterInstance<IBulkDbService>(thkGage.bulkDb);





            Startup startup = container.Resolve<Startup>();


            StartOptions options = new StartOptions($"http://{ServerAddr}/");
            //http://localhost:10010/swagger/ui/index 有说明文档

            webApp = Microsoft.Owin.Hosting.WebApp.Start(options, startup.Configuration);
            IsRunning = true;
        }
        public void Stop() 
        {
            if (webApp != null) {
                webApp.Dispose();
                webApp = null;
                IsRunning = false;
            }
        }

        string file_path = "thickwebapi.json";
        bool Load()
        {
            try
            {
                if (File.Exists(file_path))
                {
                    string json = File.ReadAllText(file_path);
                    var jsonDb = JsonConvert.DeserializeObject<ThickWebApiServerJsonDb>(json);
                    this.ServerAddr = jsonDb.ServerAddr;
                    return true;
                }
            }
            catch
            {
                //异常，没有json 解码失败

            }
            return false;
        }

        /// <summary>
        /// 保存参数
        /// </summary>
        /// <returns></returns>
        public bool Save()
        {
            try
            {
                var jsonDb = new ThickWebApiServerJsonDb() { ServerAddr = ServerAddr };
                string json = JsonConvert.SerializeObject(jsonDb, Formatting.Indented);
                File.WriteAllText(file_path, json);
                return true;
            }
            catch
            {
                //异常，没有json 编码失败

            }
            return false;
        }
    }

    /// <summary>
    /// ThickWebApiServer 的参数
    /// </summary>
    public class ThickWebApiServerJsonDb
    {
        /// <summary>
        /// 服务地址
        /// </summary>
        public string ServerAddr = "0.0.0.0:10010";
    }
}
