using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Media;
using TDx.SpaceMouse.Navigation3D;
using log4net;
using System.Windows;
using System.Windows.Interop;
using System.Runtime.InteropServices;
using System.Runtime.CompilerServices;

namespace VIZ.Framework.Core
{
    /// <summary>
    /// 3D鼠标管理器
    /// </summary>
    public static class Navigation3DManager
    {
        /// <summary>
        /// 日志
        /// </summary>
        private static readonly ILog log = LogManager.GetLogger(typeof(Navigation3DManager));

        /// <summary>
        /// 3D鼠标数据信息
        /// </summary>
        public static volatile Navigation3DDataInfo Info = new Navigation3DDataInfo();

        /// <summary>
        /// 初始化
        /// </summary>
        /// <param name="window">关联的额窗口</param>
        public static void Init(Window window)
        {
            if (window == null)
                return;

            try
            {
                WindowInteropHelper windowInteropHelper = new WindowInteropHelper(window);

                // 初始化3D鼠标
                bool init_result = Navigation3DHelper.init_3D_Mouse(windowInteropHelper.Handle);

                // 注册窗口消息
                HwndSource source = HwndSource.FromHwnd(windowInteropHelper.Handle);
                source.AddHook(Hook);
            }
            catch (Exception ex)
            {
                log.Error(ex);
            }
        }

        /// <summary>
        /// 销毁
        /// </summary>
        public static void Dispose()
        {
            try
            {
                Navigation3DHelper.dispose_3D_Mouse();
            }
            catch (Exception ex)
            {
                log.Error(ex);
            }
        }

        /// <summary>
        /// 处理窗口消息
        /// </summary>
        private static IntPtr Hook(IntPtr hwnd, int msg, IntPtr wparam, IntPtr lparam, ref bool handled)
        {
            try
            {
                IntPtr data_ptr = Navigation3DHelper.on_message_3D_Mouse(wparam, lparam);
                Navigation3DData data = Marshal.PtrToStructure<Navigation3DData>(data_ptr);
                Navigation3DHelper.dispose_3D_Mouse_data(data_ptr);

                if (data.result == 1)
                {
                    Info.tx = data.tx;
                    Info.ty = data.ty;
                    Info.tz = data.tz;
                    Info.rx = data.rx;
                    Info.ry = data.ry;
                    Info.rz = data.rz;
                }
            }
            catch (Exception ex)
            {
                log.Error(ex);
            }

            return new IntPtr(1);
        }
    }
}
