/*******************************************************************************
 * Copyright (c) 2012 by Thomas Jahn
 * Questions? Mail me at lithander@gmx.de!
 ******************************************************************************/
package net.pixelpracht.geometry
{
	public class Sector
	{
		public var alpha:Number;
		public var theta:Number;
		
		private function get beta():Number
		{
			return alpha + theta;			
		}
		
		public function Sector(alphaRadian:Number = 0, betaRadian:Number = 0)
		{
			alpha = alphaRadian;
			theta = betaRadian - alphaRadian;
		}
			
		public function clear():void
		{
			alpha = theta = 0;	
		}
		
		public function setFullCircle():void
		{
			alpha = 0;
			theta = Angle.TwoPI;
		}
		
		public function setCone(dir:Vector2D, coneAngle:Number, normalize:Boolean = false):void
		{
			alpha = Math.atan2(dir.y, dir.x) - 0.5 * coneAngle;
			if(normalize)
				alpha = Angle.normalizeRad2(alpha);
			theta = coneAngle;
		}
		
		public function setFromCoords(cx:Number, cy:Number, ax:Number, ay:Number, bx:Number, by:Number, normalize:Boolean = false):void
		{
			alpha = Math.atan2(ay-cy, ax-cx);
			var newBeta:Number = Math.atan2(by-cy, bx-cx);
			if(normalize)
			{	
				alpha = Angle.normalizeRad2(alpha);
				newBeta = Angle.normalizeRad2(newBeta);
			}
			if(alpha >= newBeta)
				alpha = theta = 0;	//clear
			else
				theta = newBeta - alpha;
		}
		
		public function copy(a:Sector):void
		{
			alpha = a.alpha;
			theta = a.theta;		
		}
		
		public function setIntersection(a:Sector, b:Sector):void
		{
			if(a.theta == 0 || b.theta == 0)
				alpha = theta = 0;	//clear
			else
			{
				alpha = Math.max(a.alpha, b.alpha);
				var newBeta:Number = Math.min(a.alpha + a.theta, b.alpha + b.theta);
				if(newBeta <= alpha)
					alpha = theta = 0;//clear
				else
					theta = newBeta - alpha;				
			}
		}

		public function setUnion(a:Sector, b:Sector):void
		{
			if(a.theta == 0)
			{
				//copy b
				alpha = b.alpha;
				theta = b.theta;
			}
			else if(b.theta == 0)
			{
				//copy a
				alpha = a.alpha;
				theta = a.theta;
			}
			else
			{
				alpha = Math.min(a.alpha, b.alpha);
				var newBeta:Number = Math.max(a.beta, b.beta);
				if(newBeta <= alpha)
					alpha = theta = 0;	//clear
				else
					theta = newBeta - alpha;
			}
		}		
	}
}