using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using VIZ.Framework.Connection;
using log4net;
using System.Diagnostics;
using VIZ.Framework.Core;

namespace VIZ.Framework.Module
{
    /// <summary>
    /// 3D鼠标命令行解释器
    /// </summary>
    public class Navigation3DCommandProvider : ConnCommandLinePackageProvider
    {
        /// <summary>
        /// 日志
        /// </summary>
        private readonly static ILog log = LogManager.GetLogger(typeof(Navigation3DCommandProvider));

        /// <summary>
        /// 3D鼠标命令行解释器
        /// </summary>
        /// <param name="mappings">映射集合</param>
        public Navigation3DCommandProvider(List<Navigation3DMapping> mappings)
        {
            this.Mappings = mappings;
        }

        /// <summary>
        /// 映射值
        /// </summary>
        public List<Navigation3DMapping> Mappings { get; private set; }

        /// <summary>
        /// 执行命令
        /// </summary>
        /// <param name="info">命令行信息</param>
        protected override void Execute(ConnCommandLineInfo info)
        {
            if (this.Mappings == null || this.Mappings.Count == 0)
                return;

            string[] args = info.Command.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
            string cmd = null;
            int value1 = 0;
            int value2 = 0;
            if (args.Length >= 1)
            {
                cmd = args[0];
            }
            if (args.Length >= 2)
            {
                int.TryParse(args[1], out value1);
            }
            if (args.Length >= 3)
            {
                int.TryParse(args[2], out value2);
            }

            int temp = Math.Abs(value2);

            Navigation3DMapping first = this.Mappings.FirstOrDefault();
            Navigation3DMapping last = this.Mappings.LastOrDefault();

            Navigation3DTcpManager.Command = cmd;

            if (temp == 0 || temp < first.MinValue)
            {
                Navigation3DTcpManager.Value = 0;
                Navigation3DTcpManager.MappingValue = 0;

                return;
            }

            if (temp >= last.MaxValue)
            {
                Navigation3DTcpManager.Value = value2;
                Navigation3DTcpManager.MappingValue = (value2 > 0 ? 1 : -1) * last.MappingValue;

                return;
            }

            Navigation3DMapping mapping = this.Mappings.FirstOrDefault(p => temp >= p.MinValue && temp < p.MaxValue);
            if (mapping == null)
                return;

            Navigation3DTcpManager.Value = value2;
            Navigation3DTcpManager.MappingValue = (value2 > 0 ? 1 : -1) * mapping.MappingValue;
        }
    }
}
