'''
Created on Apr 22, 2011
@author: Dilum Bandara
@version: 0.1
@copyright: Copyright(c) 2011, Dilum Bandara
@license: GPL
'''

class CentralNode(object):
    '''
    Central node class. Keep the resource index
    '''


    def __init__(self, id):
        '''        
        @param id: Node ID
        '''
        self._id = id
        self._idx = {}
        self._num_que_ans = 0
        self._num_que_msg_rec = 0 #Number of queries
        self._num_updates_msgs_rec = 0 #Number of updates
        
    
    def add_to_index(self, source, atts):
        '''
        Add resource to index
        @param source: Source Node ID 
        @param atts: Attribute set
        @return: Success/Failure
        '''
        self._idx[source] = atts
        self._num_updates_msgs_rec += 1
        return True
    
        
    def query_index(self, que_msg):
        '''
        Check whether index has what is need to satisfy query. Here we assume that
        a resource specify all the possible attributes at least by using a perdefined
        attribute value to indicate nonexistance        
        @param que_msg: query message (BaseQueryMessage object)
        @return: Updated query message 
        '''
        self._num_que_msg_rec += 1
        results = []
        att_to_que = []
        n = que_msg.n - que_msg.num_res_found #How many resources required
        for i in range(len(que_msg.query)): #List of attributes to query
            att_to_que.append(que_msg.query[i][0])
        for i in self._idx: #Check all entries
            attribs_match = False
            for j in range(len(self._idx[i])): #For each entry check all attribs
                tmp_att_name = self._idx[i][j][0]
                if tmp_att_name in att_to_que: #Does the query ask this attribute
                    if (que_msg.query[att_to_que.index(tmp_att_name)][1] \
                            <= self._idx[i][j][1]) and (self._idx[i][j][1] <= \
                            que_msg.query[att_to_que.index(tmp_att_name)][2]):
                        attribs_match = True
                    else: #At least one attribute mismatch
                        attribs_match = False
                        break
            if attribs_match == True: #If all required attributes match
                results.append(self._idx[i])
                if len(results) == n: break #found enough resources
        if len(results) > 0:
            self._num_que_ans += 1
            que_msg.num_res_found += len(results)
        return que_msg 


    def get_stat(self):
        '''
        Get statistics
        @return: Statistics as a list
        '''
        return [self._id, self._num_que_ans, self._num_que_msg_rec, \
                self._num_updates_msgs_rec]

