using System;
using GraphiXNA.Cameras;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using GraphiXNA.Graphics;

namespace GraphiXNA.Materials
{
    public class Goochy : MaterialEffect
    {
        public Texture2D ColorTexture = null;

        private Light _Light = new Light(new Vector3(0, -1, 1));

        public Goochy(GraphicsDevice graphicsDevice)
            : base(graphicsDevice)
        {
            _Effect = ResourceManager.GetGoochyEffect(GraphicsDevice, false);
        }


        public Light Light
        {
            get { return _Light; }
            set
            {
                if (value == null)
                {
                    throw new ArgumentNullException();
                }
                _Light = value;
            }
        }

        public override void SetWorld(Camera camera, ref Matrix world)
        {
            _Effect.Parameters["WorldViewProj"].SetValue(world * camera._ViewProjection);
            _Effect.Parameters["World"].SetValue(world);
            _Effect.Parameters["WorldIT"].SetValueTranspose(Matrix.Invert(world));
            _Effect.Parameters["CameraPosition"].SetValue(camera.Position);
        }

        internal override void OnBegin()
        {
            _Effect.Parameters["LightDirection"].SetValue(_Light.Direction);
            _Effect.Parameters["LightPosition"].SetValue(_Light.Position);
            _Effect.Parameters["LightRange"].SetValue(_Light.Range);
            _Effect.Parameters["LightSpotInnerCone"].SetValue(_Light.SpotInnerCone);
            _Effect.Parameters["LightSpotOuterCone"].SetValue(_Light.SpotOuterCone);

            if (ColorTexture == null)
            {
                if (_Light.LightT == Light.LightType.Directional)
                {
                    _Effect.CurrentTechnique = _Effect.Techniques[0];
                }
                else if (_Light.LightT == Light.LightType.Point)
                {
                    _Effect.CurrentTechnique = _Effect.Techniques[2];
                }
                else if (_Light.LightT == Light.LightType.Spot)
                {
                    _Effect.CurrentTechnique = _Effect.Techniques[4];
                }
            }
            else
            {
                _Effect.Parameters["ColorMap"].SetValue(ColorTexture);
                if (_Light.LightT == Light.LightType.Directional)
                {
                    _Effect.CurrentTechnique = _Effect.Techniques[1];
                }
                else if (_Light.LightT == Light.LightType.Point)
                {
                    _Effect.CurrentTechnique = _Effect.Techniques[3];
                }
                else if (_Light.LightT == Light.LightType.Spot)
                {
                    _Effect.CurrentTechnique = _Effect.Techniques[5];
                }
            }

            //_Effect.CommitChanges();
        }
    }
}
