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

using EVE.EVECameras;
using EVE.EVEShaders;
using EVE.EVEObjects.EVEObjectComponents;

namespace EVE.EVEObjects {
	public class EVESkybox : EVEObject, IEVEChildRenderer, IEVELoadable {
		private EVETexturedQuad[] mySides;
		private string[] myFiles;
		private Vector3[] myOffsets;

		public EVESkybox(string[] textures) {
			myFiles = textures;
			myScaling = new Vector3(500, 500, 500);
			mySides = new EVETexturedQuad[6];

			CreateSides();
			CalculateOffsets();
		}

		public void RenderChildren(GraphicsDevice myDevice) {
			EVEShader objShader = EVEShaderManager.GetShader(myShader);

			objShader.Effect.Begin();
			foreach(EffectPass pass in objShader.Effect.CurrentTechnique.Passes) {
				for(int i = 0; i < 6; i++) {
					mySides[i].Position = EVECameraManager.ActiveCamera.Position + myOffsets[i];
					objShader.SetParameters(mySides[i]);

					pass.Begin();
					mySides[i].Render(myDevice);
					pass.End();
				}
			}
			objShader.Effect.End();
		}

		public void LoadGraphicsContent(GraphicsDevice myDevice, ContentManager myLoader) {
			foreach(EVETexturedQuad quad in mySides) {
				quad.LoadGraphicsContent(myDevice, myLoader);
			}
		}

		private void CreateSides() {
			for(int i = 0; i < 6; i++) {
				mySides[i] = new EVETexturedQuad(myFiles[i]);
				mySides[i].Scaling = myScaling;
			}

			mySides[0].Rotation = Quaternion.CreateFromAxisAngle(new Vector3(1, 0, 0), MathHelper.PiOver2);
			mySides[1].Rotation = Quaternion.CreateFromAxisAngle(new Vector3(1, 0, 0), -MathHelper.PiOver2);
			mySides[2].Rotation = Quaternion.CreateFromAxisAngle(new Vector3(0, 1, 0), MathHelper.PiOver2);
			mySides[3].Rotation = Quaternion.CreateFromAxisAngle(new Vector3(0, 1, 0), -MathHelper.PiOver2);
			mySides[5].Rotation = Quaternion.CreateFromAxisAngle(new Vector3(0, 1, 0), MathHelper.Pi);
		}

		private void CalculateOffsets() {
			myOffsets = new Vector3[6];

			myOffsets[0] = new Vector3(0, 0.5f, 0) * myScaling;
			myOffsets[1] = new Vector3(0, -0.5f, 0) * myScaling;
			myOffsets[2] = new Vector3(-0.5f, 0, 0) * myScaling;
			myOffsets[3] = new Vector3(0.5f, 0, 0) * myScaling;
			myOffsets[4] = new Vector3(0, 0, -0.5f) * myScaling;
			myOffsets[5] = new Vector3(0, 0, 0.5f) * myScaling;
		}
	}
}