from Texture import *
from Thing import *
import globalVars
import pygame
from pygame.locals import *
from math import *


class Alien(Thing):

    alienTex = None

    def __init__(self):
        Thing.__init__(self)
        if(Alien.alienTex == None):
            Alien.alienTex = Texture("alien1", group=1)
        self.texture = Alien.alienTex
        self.move_speed = 0.5
        
        self.health = 100
        self.dead = 0
        
        self.damage = 1
        
    def draw(self):
        self.texture.draw(pos=(self.x, self.y))
        
    """def update(self, delta):
        Thing.update(self, delta)
        self.draw()"""
        
    def collideLight(self, light):
        if self.x + 16.0 > light.xMin and self.x + 16.0< light.xMax \
           and self.y + 16.0> light.yMin and self.y + 16.0< light.yMax:
            return self.advancedCollide(light)
        else:
            return False
            
    def hit(self, damage):
        self.health -= damage
        if self.health <= 0:
            self.dead = 1
            
    def advancedCollide(self, light):
    
        # self - origin
        a = self.x + 16.0- light.origin[0], self.y + 16.0- light.origin[1]
        
        # origin - end  
        b = light.xEnd - light.origin[0], light.yEnd - light.origin[0]
    
        dp = a[0]*b[0] + a[1]*b[1]
        
        proj = [0,0]
    
        proj[0] = ( dp / (b[0]*b[0] + b[1]*b[1]) ) * b[0];
	proj[1] = ( dp / (b[0]*b[0] + b[1]*b[1]) ) * b[1];
	
	distanceV = proj[0] - a[0], proj[1] - a[1]
	
	distance = sqrt(distanceV[0]*distanceV[0] + distanceV[1]*distanceV[1]);
	
	if abs(distance) < 40:
	    return True
	else:
	    return False
	
	

    def moveMe(self, target):
        inLight = 0
        closestLight = None
        
        direction = 1.0 # set to -1 to move away from.
        
        for li in globalVars.lightList:
            if self.collideLight(li):
                inLight = 1
                closestLight = li

        if inLight:
            direction = - 1.0
            target = (closestLight.origin[0], closestLight.origin[1])
            self.move_speed = 0.5
        else:
            self.move_speed = 0.75
        
        if self.x > target[0]:
            self.setSpeed(x = -self.move_speed * direction)
        elif self.x < target[0]:
            self.setSpeed(x = self.move_speed * direction)
        if self.y > target[1]:
            self.setSpeed(y = -self.move_speed * direction)
        elif self.y < target[1]:
            self.setSpeed(y = self.move_speed * direction)
