import { Ray } from './math/Ray';
import { Vector2 } from './math/Vector2';
import { Vector3 } from "./math/Vector3"
import { Camera } from './cameras/Camera';
import { Object3D } from './Object3D';
import { Mesh3D } from './Mesh3D';

//射线检测工具，暂时不对外导了

export class Raycaster {
	public ray: Ray
	constructor(
		origin?: Vector3,
		direction?: Vector3,
		public near: number = 0,
		public far: number = Infinity
	) {
		this.ray = new Ray(origin, direction);
	}
	set(origin: Vector3, direction: Vector3) {
		this.ray.set(origin, direction);
	}
	setFromCamera(coords: Vector3, camera: Camera) {

		// if ( ( camera && camera.isPerspectiveCamera ) ) {

		this.ray.origin.setFromMatrixPosition(camera._worldMatrix);
		this.ray.direction.set(coords.x, coords.y, 0.5).unproject(camera).sub(this.ray.origin).normalize();

		// } else if ( ( camera && camera.isOrthographicCamera ) ) {

		// 	this.ray.origin.set( coords.x, coords.y, ( camera.near + camera.far ) / ( camera.near - camera.far ) ).unproject( camera ); // set origin in plane of camera
		// 	this.ray.direction.set( 0, 0, - 1 ).transformDirection( camera.matrixWorld );

		// } else {

		// 	console.error( 'THREE.Raycaster: Unsupported camera type.' );

		// }

	};

	intersectObject(object: Object3D, optionalTarget?: IntersectData[]) {

		var intersects = optionalTarget || [];

		intersectObject(object, this, intersects);

		intersects.sort(ascSort);

		return intersects;

	}
}

function ascSort(a: IntersectData, b: IntersectData) {
	return a.distance - b.distance;
}

function intersectObject(object: Object3D, raycaster: Raycaster, intersects: IntersectData[]) {

	if (object.visible === false) return;

	if (object.mouseEnable) object.raycast(raycaster, intersects);

	if (object.mouseChildren) {
		var children = object.children;
		for (var i = 0, l = children.length; i < l; i++) {
			intersectObject(children[i], raycaster, intersects);
		}
	}
}

export interface IntersectData {
	distance: number,
	point?: Vector3,
	object: Object3D,
	uv?: Vector2,//以后再说
	// face?:Face3,
}
