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

import datetime
import json
import uuid

from txosc import dispatch
from txosc.osc import getAddressParts
from txosc.async import DatagramServerProtocol

import ntplib

from dateutil.tz import tzutc

from baseserver import BaseProtocol
import utils


class OSCServerProtocol(DatagramServerProtocol, BaseProtocol):
    """
    Receive UDP OSC messages
    """

    def __init__(self, ws_factory, conn):
        self.receiver = dispatch.Receiver()
        self.receiver.addCallback("/pianoroll/*/", self.processPianorollAnnotation)
        self._init_props(ws_factory, conn)

    def processPianorollAnnotation(self, message, address):

        values = message.getValues()
        ts = datetime.datetime.fromtimestamp(ntplib.ntp_to_system_time(values[0]), tzutc())

        params = {
            'ts' : ts,
            'event_code': getAddressParts(message.address)[1],
            'channel' : utils.PIANOROLL_CHANNEL,
            'content' : values
        }

        self.process_annotation(params)
