using log4net;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using VIZ.Framework.Core;
using VIZ.Package.Domain;
using VIZ.Package.Storage;

namespace VIZ.Package.Service
{
    /// <summary>
    /// Viz控制对象下载服务
    /// </summary>
    public class VizControlObjectDownloadService
    {
        /// <summary>
        /// 日志
        /// </summary>
        private readonly static ILog log = LogManager.GetLogger(typeof(VizControlObjectDownloadService));

        /// <summary>
        /// Viz命令控制对象服务
        /// </summary>
        private VizCommandControlObjectService vizCommandControlObjectService = new VizCommandControlObjectService();

        /// <summary>
        /// Viz命令服务
        /// </summary>
        private VizCommandService vizCommandService = new VizCommandService();

        /// <summary>
        /// 控制对象服务
        /// </summary>
        private ControlObjectService controlObjectService = new ControlObjectService();

        /// <summary>
        /// 加载
        /// </summary>
        /// <param name="pageBases"></param>
        public void Load(List<PageModelBase> pageBases)
        {
            // 停止更新
            this.vizCommandService.SetEnabledUpdate(ApplicationDomainEx.PreviewConn, false);

            // 更新场景
            foreach (PageModelBase page in pageBases)
            {
                try
                {
                    Debug.WriteLine($"加载场景 开始 [ {page.Scene} ]");

                    this.ExecuteLoadOnePage(page);

                    Debug.WriteLine($"加载场景 结束 [ {page.Scene} ]");
                }
                catch (Exception ex)
                {
                    log.Error(ex);
                }
            }

            // 启用更新
            this.vizCommandService.SetEnabledUpdate(ApplicationDomainEx.PreviewConn, true);
        }

        /// <summary>
        /// 执行加载
        /// </summary>
        /// <param name="pageBase">模板或页</param>
        private void ExecuteLoadOnePage(PageModelBase pageBase)
        {
            if (pageBase == null)
                return;

            // 切换场景
            this.vizCommandService.SetObject(ApplicationDomainEx.PreviewConn, pageBase.ScenePath, pageBase.Layer);

            // 获取控制对象
            ControlObjectModel controlObject = this.vizCommandControlObjectService.GetControlObject(ApplicationDomainEx.PreviewConn);

            // 保存控制对象到本地
            this.controlObjectService.SaveControlObject(pageBase, controlObject);

            // 保存控制对象字段到本地
            this.controlObjectService.SaveControlFields(pageBase, controlObject.AllFiledNodes);
        }
    }
}
