using System;
using System.Collections.Generic;
using Encompass;
using Kav;
using KavTest.Components;
using Microsoft.Xna.Framework.Graphics;

namespace KavTest.Renderers
{
    public class SceneRenderer : GeneralRenderer
    {
        private GraphicsDevice GraphicsDevice { get; }

        private IEnumerable<Kav.Model> Models
        {
            get
            {
                foreach (var entity in ReadEntitiesAsEnumerable<ModelComponent>())
                {
                    var transformComponent = GetComponent<TransformComponent>(entity);
                    var modelComponent = GetComponent<ModelComponent>(entity);

                    modelComponent.Model.ApplyTransform(transformComponent.Transform);
                    yield return modelComponent.Model;
                }
            }
        }

        private IEnumerable<PointLight> PointLights
        {
            get
            {
                foreach (var entity in ReadEntitiesAsEnumerable<PointLightComponent>())
                {
                    var transformComponent = GetComponent<TransformComponent>(entity);
                    var pointLightComponent = GetComponent<PointLightComponent>(entity);

                    yield return new PointLight(
                        transformComponent.Transform.Translation,
                        pointLightComponent.Color,
                        pointLightComponent.Intensity
                    );
                }
            }
        }

        public SceneRenderer(GraphicsDevice graphicsDevice)
        {
            GraphicsDevice = graphicsDevice;
        }

        public override void Render()
        {
            if (SomeComponent<CameraComponent>())
            {
                var cameraComponent = ReadComponent<CameraComponent>();

                Kav.Renderer.Render(
                    GraphicsDevice,
                    cameraComponent.Camera,
                    Models,
                    PointLights
                );
            }
        }
    }
}
