using System;
using System.Collections.Generic;
using Microsoft.Xna.Framework;
using Jitter.LinearMath;

namespace KinPortal {
	public class PortalCollisionStrategy : CollisionStrategy {
		public void Update(InterruptorObject obj, GameTime gameTime) {
		
		}

		public void Collision(InterruptorObject hostObj, DynamicObject obj) {
			Portal inPortal = null;
			Portal outPortal = null;

			if(obj.IsStatic == true) {
				return;
			}

			if(hostObj == hostObj.Scene.PortalManager.BluePortal) {
				inPortal = (Portal) hostObj;
				outPortal = hostObj.Scene.PortalManager.RedPortal;
			}

			if(hostObj == hostObj.Scene.PortalManager.RedPortal) {
				inPortal = (Portal) hostObj;
				outPortal = hostObj.Scene.PortalManager.BluePortal;
			}

			if(inPortal != null && outPortal != null) {
				Vector3 relPos = obj.Pos - inPortal.Pos;
				if(Vector3.Dot(Vector3.Normalize(relPos), inPortal.Normal) < 0.35f) {
					return;
				}

				Vector3 axis;
				Quaternion rot;
				if(inPortal.Rot == outPortal.Rot) {
					rot = Quaternion.Identity;
					axis = outPortal.Up;
				} else {
					rot = outPortal.Rot * Quaternion.Conjugate(inPortal.Rot);
					//axis = Geometry.GetRotationAxis(rot);
					axis = outPortal.Up;
				}
				obj.Pos = outPortal.Pos + Vector3.Transform(relPos, rot) * 1.2f;
				Quaternion rot2 = rot * Quaternion.CreateFromAxisAngle(axis, (float) Math.PI);
				obj.Rot = obj.Rot * rot2;
				Vector3 vel = Geometry.GetXnaVector(obj.PhysicModel.LinearVelocity);
				obj.PhysicModel.LinearVelocity = Geometry.GetJitterVector(Vector3.Transform(-vel, rot));
			}
		}
	}
}
