'''
Created on Nov 26, 2011
Modified on Jan 3, 2012
@version: 0.3
@author: Dilum Bandara
@email: dilumb@engr.colostate.edu
@copyright: Copyright(c) 2011, Dilum Bandara
@license: GPL
'''

import math
import Config as Config

def dist(point1, point2):
    '''
    Distance between 2 points
    @param point1: Location 1
    @param point2: Location 2
    @return: Distance 
    '''
    dX = point2.x - point1.x
    dY = point2.y - point1.y
    return math.sqrt(dX * dX + dY * dY)


def distZone(point, zone):
    '''
    Distance between a point and closest edge of a zone
    @param point1: Location 1
    @return: Distance 
    '''
    dist = 0
    if (point.x < zone[0].x) or (zone[1].x < point.x): #If outside x-axis of zone
        dX1 = point.x - zone[0].x
        dX2 = point.x - zone[1].x
        dist += min(dX1 * dX1, dX2 * dX2)
    if (point.y < zone[0].y) or (zone[1].y < point.y):
        dY1 = point.y - zone[0].y
        dY2 = point.y - zone[1].y
        dist += min(dY1 * dY1, dY2 * dY2)
    return  math.sqrt(dist)


def inRange(point1, point2, nodeRange):
    '''
    Are 2 points within given range
    @param point1: Location 1
    @param point2: Location 2
    @param nodeRange: Range 
    @return: True or False
    '''
    if dist(point1, point2) <= nodeRange: return True
    else: return False

    
def inZone(zone, point, considerBoundary = False):
    '''
    Check whether given point is within rectangular zone. Check zone boundary
    @param zone: rectangular area
    @param point: Point to be checked
    @return: Success or failure  
    '''
    matchX = False
    matchY = False
    #At x-boundary
    if (zone[1].x == Config.SIZE_TORUS.x) or (considerBoundary == True): 
        if (zone[0].x <= point.x) and (zone[1].x >= point.x): matchX = True
    else:
        if (zone[0].x <= point.x) and (zone[1].x > point.x): matchX = True
    #At y-boundary
    if (zone[1].y == Config.SIZE_TORUS.y) or (considerBoundary == True):
        if (zone[0].y <= point.y) and (zone[1].y >= point.y): matchY = True
    else:
        if (zone[0].y <= point.y) and (zone[1].y > point.y): matchY = True
    if matchX == True and matchY == True: return True
    else: return False


