import copy

__all__ = 'HandlerEvent',


class HandlerEvent:
    tb = 'event'

    def __init__(self, db_client, db_name, ipsearch):
        self.event = dict()
        self.db_client = db_client
        self.db_name = db_name
        self.ipsearch = ipsearch

    def set_region(self, data):
        ip = data.get('#ip')
        if ip:
            data['#country'], data['#province'], data['#city'] = self.ipsearch.search(ip)

    def merge_update(self, a: dict, b: dict):
        """
        可更新事件 合并
        :param a:
        :param b:
        :return:
        """
        if 'properties' not in b or not isinstance(b['properties'], dict):
            return
        for k, v in b['properties'].items():
            a[k] = v

    def track(self, data):
        self.set_region(data)
        self.event[len(self.event)] = data

    def track_update(self, data):
        if '#event_id' not in data:
            return
        self.set_region(data)
        old_event = self.db_client.get_one(self.db_name, self.tb, {'#event_id': data['#event_id']})
        old_event['sign'] = -1
        self.event[len(self.event)] = old_event

        new_event = copy.deepcopy(old_event)
        self.merge_update(new_event, data)
        new_event['sign'] = 1
        self.event[len(self.event)] = new_event

    def track_overwrite(self, data):
        if '#event_id' not in data:
            return
        self.set_region(data)
        old_event = self.db_client.get_one(self.db_name, self.tb, {'#event_id': data['#event_id']})
        old_event['sign'] = -1
        self.event[len(self.event)] = old_event

        self.event[len(self.event)] = data

    @property
    def buffer_pool(self):
        return self.tb, self.event
