using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Content;

using EVE.EVEObjects.EVEObjectComponents;
using EVE.EVEShaders;
using EVE.EVEAssets;

namespace EVE.EVEObjects {
	public class EVEModel : EVEObject, IEVELoadable, IEVEChildRenderer, IEVEHasMaterial {
		private string myAsset;
		private Model myModel;

		public EVEModel(string asset) {
			myAsset = asset;
            myModel = EVEModelManager.GetModelAsset(myAsset);
		}

		public void LoadGraphicsContent(GraphicsDevice myDevice, ContentManager myLoader) {
			//myModel = myLoader.Load<Model>(myAsset);
            myModel = EVEModelManager.GetModelAsset(myAsset);
		}

		public void RenderChildren(GraphicsDevice myDevice) {
			EVEShader shader = EVEShaderManager.GetShader(myShader);
			shader.SetParameters(this);

			foreach(ModelMesh mesh in myModel.Meshes) {
				myDevice.Indices = mesh.IndexBuffer;

				shader.Effect.Begin();
				foreach(EffectPass pass in shader.Effect.CurrentTechnique.Passes) {
					pass.Begin();

					foreach(ModelMeshPart part in mesh.MeshParts) {
						myDevice.VertexDeclaration = part.VertexDeclaration;
						myDevice.Vertices[0].SetSource(
							mesh.VertexBuffer,
							part.StreamOffset,
							part.VertexStride
						);

						myDevice.Textures[0] = ((BasicEffect)part.Effect).Texture;

						myDevice.DrawIndexedPrimitives(
							PrimitiveType.TriangleList,
							part.BaseVertex, 0,
							part.NumVertices,
							part.StartIndex,
							part.PrimitiveCount
						);
					}

					pass.End();
				}
				shader.Effect.End();
			}
		}

		#region IEVEHasMaterial Members
		private Vector3 myAmbientLightColor = new Vector3(0.25f, 0.25f, 0.25f);
		private Vector3 myDiffuseColor = new Vector3(0.50f, 0.50f, 0.50f);
		private float mySpecularPower = 64;

		public void SetAmbientLightColor(Vector3 newColor) {
			myAmbientLightColor = newColor;
		}

		public void SetDiffuseColor(Vector3 newColor) {
			myDiffuseColor = newColor;
		}

		public void SetSpecularPower(float newPower) {
			mySpecularPower = newPower;
		}

		public void SetMaterialProperties() {
			Effect effect = EVEShaderManager.GetShader(myShader).Effect;
			
			if(effect.Parameters["AmbientLightColor"] != null)
				effect.Parameters["AmbientLightColor"].SetValue(myAmbientLightColor);
			
			if(effect.Parameters["DiffuseColor"] != null)
				effect.Parameters["DiffuseColor"].SetValue(myDiffuseColor);

			if(effect.Parameters["SpecularPower"] != null)
				effect.Parameters["SpecularPower"].SetValue(mySpecularPower);
		}
		#endregion
	}
}