package org.cocos2d.types.util;

import org.cocos2d.cocoa.CCGeometry.CCPoint;
import org.cocos2d.support.CCPointExtension;
import org.cocos2d.types.CGAffineTransform;

public final class CGPointUtil {
	
	/**
	 * Multiply point by floating, write result in the same point.
	 * @param v - src/dst point
	 * @param s - factor value
	 */
	public static void mult(CCPoint v, float s) {
		v.x *= s;
		v.y *= s;
	}
	
	/**
	 * Multiply point by floating, write result in another point.
	 * @param v - src point
	 * @param s - factor value
	 * @param res - dst point
	 */
	public static void mult(CCPoint v, float s, CCPoint res) {
		res.x = v.x * s;
		res.y = v.y * s;		
	}
	
	public static void applyAffineTransform(CCPoint p, CGAffineTransform t, CCPoint res) {
		applyAffineTransform(p.x, p.y, t, res);
	}
	
	public static void applyAffineTransform(float x, float y, CGAffineTransform t, CCPoint res) {
		res.x = (float) (x * t.m00 + y * t.m01 + t.m02);
		res.y = (float) (x * t.m10 + y * t.m11 + t.m12);
	}
	
	public static void zero(CCPoint p) {
		p.x = 0;
		p.y = 0;
	}

	public static void normalize(CCPoint src, CCPoint dst) {
		float invLen = 1 / CCPointExtension.ccpLength(src);
		dst.setPoint(src.x * invLen, src.y * invLen);
	}

	public static void add(CCPoint first, CCPoint second, CCPoint ret) {
		ret.x = first.x + second.x;
		ret.y = first.y + second.y;
	}

	public static void add(CCPoint v, CCPoint toAdd) {
		v.x += toAdd.x;
		v.y += toAdd.y;
	}

	public static void sub(CCPoint first, CCPoint second, CCPoint ret) {
		ret.x = first.x - second.x;
		ret.y = first.y - second.y;
	}
	
	public static void sub(CCPoint v, CCPoint toAdd) {
		v.x -= toAdd.x;
		v.y -= toAdd.y;
	}

	public static float distance(CCPoint p1, CCPoint p2) {
		float dx = p2.x - p1.x;
		float dy = p2.y - p1.y;
		return (float)Math.sqrt(dx * dx + dy * dy);
	}
	
	public static void rotateByAngle(CCPoint v, CCPoint pivot, float angle, CCPoint ret) 
	{
		CGPointUtil.sub(v, pivot,ret);
		float t = ret.x;
		float cosa = (float)Math.cos(angle);
		float sina = (float)Math.sin(angle);
		ret.x = t*cosa - ret.y*sina;
		ret.y = t*sina + ret.y*cosa;
		CGPointUtil.add(ret, pivot);
	}
}
