##########################################
## Copyright 2012-2013 Ceruti Francesco & contributors
##
## This file is part of LiSP (Linux Show Player).
##########################################

import socket
import time
import threading
from lisp.core.events import Event


class Slave:

    def __init__(self, masterAddr, slavePort):
        self.masterAddr = masterAddr
        self.syncCmd = Event()
        self.activeSlave = Event()
        self.sSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.sSocket.bind(('', slavePort))
        self.sSocket.listen(16)
        self.acceptThread = threading.Thread(None, target=self.listen)
        self.acceptThread.setDaemon(True)
        self.acceptThread.start()

        try:
            sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            sock.connect(self.masterAddr)
            sock.send(bytes('SLAVE', 'UTF-8'))
            sock.close()
        except Exception as e:
            print(masterAddr, ': ', e)

        self.pingThread = threading.Thread(None, target=self.ping)
        self.pingThread.setDaemon(True)
        self.pingThread.start()

    def listen(self):
        while(True):
            try:
                conn = self.sSocket.accept()[0]
                data = str(conn.recv(1024), 'UTF-8')
                self.syncCmd.emit(data)
                conn.close()
            except:
                pass

    def ping(self):
        try:
            while(True):
                sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
                sock.connect(self.masterAddr)
                sock.send(bytes('PING', 'UTF-8'))
                time.sleep(0.2)
                sock.close()
        except:
            self.activeSlave.emit()
