using Plane.CopterManagement;
using Plane.Copters;
using Plane.Messaging;
using System.Collections.Generic;
using System.Linq;

namespace Plane.CopterControllers
{
    /// <summary>
    /// 集中管理所有控制器。
    /// </summary>
    public class CopterControllerManager : ICopterControllerManager
    {
        private CopterControllerBase[] _allControllers;

        private AvatarController _avatarController;

        private ICopterManager _copterManager;

        private FlyToController _flyToController;

        private KeyboardController _keyboardController;

        //private MicroController _microController;

        private HashSet<CopterState> _statesControllingRollPitch = new HashSet<CopterState> { CopterState.HoverMode, CopterState.FloatMode };

        public CopterControllerManager(IPLMessenger messenger, ICopterManager copterManager, FlyToController flyToController, AvatarController avatarController, KeyboardController keyboardController) //, MicroController microController, )
        {
            _copterManager = copterManager;
            _flyToController = flyToController;
            _avatarController = avatarController;
            //_microController = microController;
            _keyboardController = keyboardController;
            _allControllers = new CopterControllerBase[] { _flyToController, _avatarController, _keyboardController };

            messenger.Register<LandingStateAcceptsAvatarChangedMessage>(this, m =>
            {
                if (m.LandingStateAcceptsAvatar) _statesControllingRollPitch.Add(CopterState.Landing);
                else _statesControllingRollPitch.Remove(CopterState.Landing);
            });
        }

        public bool IsControllingRollPitchUsingAvatar => _avatarController.IsEnabled && _statesControllingRollPitch.Contains(_copterManager.Copter.State) && !_copterManager.Copter.IsEmergencyHoverActive;

        public void EnableCopterControllers(CopterControllerTypes controllerTypes)
        {
            foreach (var controller in _allControllers)
            {
                controller.IsEnabled = controllerTypes.HasFlag(controller.Type);
            }
        }

        public bool IsControllerEnabled(CopterControllerTypes controllerType)
        {
            var controller = _allControllers.FirstOrDefault(c => c.Type == controllerType);
            return controller?.IsEnabled ?? false;
        }
    }
}
