
#
# See LICENCE for detail
# Copyright (c) 2014 IRI
#

import copy
import datetime
import uuid
import json

from dateutil.tz import tzutc

from models import insert_annot_async

class BaseProtocol(object) :

    def _init_props(self, ws_factory, conn):
        self.conn = conn
        self.ws_factory = ws_factory


    """
    Mixin class to add helper methods
    """
    def process_annotation(self, params):

        ts = params.setdefault('ts', datetime.datetime.now(tzutc()))
        if ts.tzinfo is None:
            ts = ts.replace(tzinfo=tzutc())
            params['ts'] = ts
        uuid_val = params.setdefault('uuid', uuid.uuid4())

        params_broadcast = copy.copy(params)
        params_broadcast.update({ 'ts' : ts.isoformat() })
        params_broadcast['uuid'] = str(params_broadcast['uuid'])

        #broadcast to websocket
        self.ws_factory.broadcast(json.dumps(params_broadcast), params_broadcast)

        #TODO treat errors
        return insert_annot_async(params, self.conn)
