'''
*  This work is licensed under the Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International (CC BY-NC-SA 4.0) License.
*
*
*  To view a copy of this license, visit
*
*  German version:  http://creativecommons.org/licenses/by-nc-sa/4.0/deed.de
*  English version: http://creativecommons.org/licenses/by-nc-sa/4.0/
*
*  or send a letter to Creative Commons, 171 Second Street, Suite 300, San Francisco, California, 94105, USA.
'''


import xbmc
import xbmcaddon
import socket
import json


addon = xbmcaddon.Addon("service.wakeup.action")
addon_name = addon.getAddonInfo('name')


class WakeupAction():
    def __init__(self):
        self.XBMCIP = addon.getSetting('xbmcip')
        self.XBMCPORT = int(addon.getSetting('xbmcport'))
        
        self.s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.s.connect((self.XBMCIP, self.XBMCPORT))
        self.s.setblocking(1)
        self.methodDict = {"System.OnWake": self.SystemOnWake,
                          }

    def handleMsg(self, msg):
        jsonmsg = json.loads(msg)        
        method = jsonmsg["method"]
        if method in self.methodDict:
            methodHandler = self.methodDict[method]
            methodHandler(jsonmsg)
            

    def listen(self):
        currentBuffer = []
        msg = ""
        depth = 0
        while not xbmc.abortRequested:
            chunk = self.s.recv(1)
            currentBuffer.append(chunk)
            if chunk == '{':
                depth += 1
            elif chunk == '}':
                depth -= 1
                if not depth:
                    msg = ''.join(currentBuffer)
                    self.handleMsg(msg)
                    currentBuffer = []
        self.s.close()


    def SystemOnWake(self, jsonmsg):
        xbmc.executebuiltin("PlayMedia(plugin://plugin.audio.radio_de/station/8441)")


if __name__ == '__main__':
    WA = WakeupAction()
    WA.listen()
    del WA
