from threading import Thread

import socket
import SocketServer
import json
import datetime as dt
import select 
import time

from pyretic.examples.shared import *

class SocketData(object):
    def __init__(self):
        self.buffer = ""
        self.zeroByteMessage = False

    def receive(self, segment):
        if len(segment) == 0:
            self.zeroByteMessage = True
        self.buffer = self.buffer + segment

    def ready(self):
        return "\n" in self.buffer
        
    def closingConnection(self):
        return self.zeroByteMessage

    def getMessage(self):
        message, self.buffer = self.buffer.split("\n", 1)
        print "message from SIMS", message
        return message

class eventListener():
    def __init__(self, handler, socket):
        self.handler = handler
        self.simsSocket = socket
        
        th = Thread(target=self.event_listener)
        th.daemon = True
        th.start()
    
    def event_listener(self):
        # zdroj: http://stackoverflow.com/questions/13101653/python-convert-complex-dictionary-of-strings-from-unicode-to-ascii
        def convertToUtf8(input):
            if isinstance(input, dict):
                return {convertToUtf8(key): convertToUtf8(value) for key, value in input.iteritems()}
            elif isinstance(input, list):
                return [convertToUtf8(element) for element in input]
            elif isinstance(input, unicode):
                return input.encode('utf-8')
            else:
                return input
        # konec zdroja
        
        
        while 1:
            data = SocketData();
            
            while 1:
                data.receive(self.simsSocket.recv(1024))
                if data.closingConnection(): 
                    self.simsSocket.close()
                    break
                while data.ready():
                    unicode_dict = json.loads(data.getMessage())
                    utf8_dict = convertToUtf8(unicode_dict)
                    self.handler(utf8_dict)
            connected = False
            while not connected:
                try:
                    self.simsSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
                    self.simsSocket.connect((sims_ip, int(sims_port)))
                except:
                    time.sleep(1)
                else:
                    connected = True
            print lineNo()
