#! /usr/bin/env python
'''Libraries for events
Interactions, pedestrian crossing...'''

#import utils;
import moving

__metaclass__ = type

class Interaction(moving.STObject):
    '''Class for an interaction between two road users 
    or a road user and an obstacle
    
    link to the moving objects
    '''

    categories = {'headon': 0,
                  'rearend': 1,
                  'side': 2,
                  'parallel': 3}

    def __init__(self, num = None, timeInterval = None, roaduserNum1 = None, roaduserNum2 = None, movingObject1 = None, movingObject2 = None, categoryNum = None):
        moving.STObject.__init__(self, num, timeInterval)
        self.roaduserNum1 = roaduserNum1
        self.roaduserNum2 = roaduserNum2
        self.movingObject1 = movingObject1
        self.movingObject2 = movingObject2
        self.categoryNum = categoryNum

    def getIndicator(self, indicatorName):
        if hasattr(self, 'indicators'):
            for i in self.indicators:
                if i.name == indicatorName:
                    return i
        else:
            return None

    def computeIndicators(self):
        collisionCourseDotProduct = [0]*self.timeInterval.length()
        collisionCourseCosine = {}
        distances = [0]*self.timeInterval.length()
        for i,instant in enumerate(self.timeInterval):
            deltap = self.movingObject1.getPositionAtInstant(instant)-self.movingObject2.getPositionAtInstant(instant)
            deltav = self.movingObject2.getVelocityAtInstant(instant)-self.movingObject1.getVelocityAtInstant(instant)
            collisionCourseDotProduct[i] = moving.Point.dot(deltap, deltav)
            distances[i] = deltap.norm2()
            if collisionCourseDotProduct[i] > 0:
                collisionCourseCosine[instant] = collisionCourseDotProduct[i]/(distances[i]*deltav.norm2())
        self.indicators = [moving.SeverityIndicator('Collision Course Dot Product', collisionCourseDotProduct, self.timeInterval),
                           moving.SeverityIndicator('Distances', distances, self.timeInterval),
                           moving.SeverityIndicator('Collision Course Cosine', collisionCourseCosine)]

class Crossing(moving.STObject):
    '''Class for the event of a street crossing

    TODO: detecter passage sur la chaussee
    identifier origines et destination (ou uniquement chaussee dans FOV)
    carac traversee
    detecter proximite veh (retirer si trop similaire simultanement
    carac interaction'''
    
    def __init__(self, roaduserNum = None, num = None, timeInterval = None):
        moving.STObject.__init__(self, num, timeInterval)
        self.roaduserNum = roaduserNum

    

if __name__ == "__main__":
    import doctest
    import unittest
    #suite = doctest.DocFileSuite('tests/moving.txt')
    suite = doctest.DocTestSuite()
    unittest.TextTestRunner().run(suite)
    
