using Encompass;
using KavTest.Components;
using KavTest.Messages;

namespace KavTest.Engines
{
    [Reads(typeof(PerspectiveCameraComponent), typeof(ArcballTransformComponent))]
    [Receives(typeof(MoveCameraMessage), typeof(RotateCameraMessage))]
    [Writes(typeof(ArcballTransformComponent))]
    public class CameraEngine : Engine
    {
        public override void Update(double dt)
        {
            if (SomeComponent<PerspectiveCameraComponent>())
            {
                var cameraEntity = ReadEntity<PerspectiveCameraComponent>();
                var arcballTransformComponent = GetComponent<ArcballTransformComponent>(cameraEntity);

                var transform = arcballTransformComponent.ArcballTransform;

                foreach (var moveMessage in ReadMessages<MoveCameraMessage>())
                {
                    transform = transform.TranslateLocal(moveMessage.Translation * (float)dt);
                }

                foreach (var rotateMessage in ReadMessages<RotateCameraMessage>())
                {
                    transform = transform.RotateLocal(rotateMessage.Yaw * 0.25f * (float)dt, rotateMessage.Pitch * 0.25f * (float)dt);
                }

                SetComponent(cameraEntity, new ArcballTransformComponent(transform));
            }
        }
    }
}
