#!/usr/bin/python
import sys
import time
import pytz
import socket
from calendar import timegm
from datetime import datetime, date

diff = None

# Fake time in UTC
diff = datetime(2013,12,27,9,30,00) - datetime.utcnow() 

met = pytz.timezone("Europe/Berlin")
def current_time():
    now = datetime.utcnow()
    if diff:
        now += diff
    timestamp = timegm(now.timetuple()) + now.microsecond / 1000000.
    now = now.replace(tzinfo=pytz.utc)
    now = now.astimezone(met)
    now = now.replace(tzinfo=None)
    return now, timestamp

sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)

def send(data):
    sock.sendto(data, ('127.0.0.1', 4444))
    print >>sys.stderr, "SENT >>> ", data

def send_clock(now, ts):
    day = (now.date() - date(2013, 12, 26)).days
    since_midnight = (
        now -
        now.replace(hour=0, minute=0, second=0, microsecond=0)
    )
    since_midnight = since_midnight.seconds + since_midnight.microseconds / 1000000.

    send('room/clock/day:%d' % day)
    send('room/clock/set:%f' % ts)
    send('room/clock/midnight:%f' % since_midnight)


def main():
    while 1:
        now, ts = current_time()
        if now.year < 2000:
            print >>sys.stderr, "too soon"
            time.sleep(1)
            continue
        send_clock(now, ts)
        time.sleep(2)
        
if __name__ == "__main__":
    main()
