/**
 * Created by rockyl on 2018/11/7.
 *
 */

/**
 * 边界类
 */
export default class Bounds {
	x;
	y;
	width;
	height;
	
	constructor(x = 0, y = 0, width = 0, height = 0) {
		this.x = x;
		this.y = y;
		this.width = width;
		this.height = height;
	}

	get left() {
		return this.x;
	}

	set left(v) {
		this.x = v;
	}

	get top() {
		return this.y;
	}

	set top(v) {
		this.y = v;
	}

	get right() {
		return this.x + this.width;
	}

	set right(v) {
		this.width = v - this.x;
	}

	get bottom() {
		return this.y + this.height;
	}

	set bottom(v) {
		this.height = v - this.y;
	}

	contains(x, y) {
		return this.x <= x &&
			this.x + this.width >= x &&
			this.y <= y &&
			this.y + this.height >= y;
	}

	setTo(x, y, width, height) {
		this.x = x;
		this.y = y;
		this.width = width;
		this.height = height;
	}

	copyFrom(target) {
		this.x = target.x;
		this.y = target.y;
		this.width = target.width;
		this.height = target.height;
	}

	clone() {
		return new Bounds(this.x, this.y, this.width, this.height)
	}

	inflate(dx, dy) {
		this.x -= dx;
		this.width += 2 * dx;
		this.y -= dy;
		this.height += 2 * dy;
	}

	isEmpty() {
		return this.width <= 0 || this.height <= 0;
	}
	
	setEmpty() {
		this.x = 0;
		this.y = 0;
		this.width = 0;
		this.height = 0;
	}

	intersects(toIntersect) {
		return Math.max(this.x, toIntersect.x) <= Math.min(this.right, toIntersect.right)
			&& Math.max(this.y, toIntersect.y) <= Math.min(this.bottom, toIntersect.bottom);
	}

	containsBounds(bounds) {
		let r1 = bounds.x + bounds.width;
		let b1 = bounds.y + bounds.height;
		let r2 = this.x + this.width;
		let b2 = this.y + this.height;
		return (bounds.x >= this.x) && (bounds.x < r2) && (bounds.y >= this.y) && (bounds.y < b2) && (r1 > this.x) && (r1 <= r2) && (b1 > this.y) && (b1 <= b2);
	}

	equals(toCompare) {
		if (this === toCompare) {
			return true;
		}
		return this.x === toCompare.x && this.y === toCompare.y
			&& this.width === toCompare.width && this.height === toCompare.height;
	}

	toString() {
		const {x, y, width, height} = this;
		return "(x=" + x + ", y=" + y + ", width=" + width + ", height=" + height + ")";
	}
}
