import threading
from elementum.config import ONLY_CLIENT
from elementum.logger import log
from elementum.rpc import server_thread
from elementum.monitor import ElementumMonitor
from elementum.daemon import elementumd_thread
from elementum.osarch import PLATFORM

import xbmc

def run():
    # Make sure the XBMC jsonrpc server is started.
    xbmc.startServer(xbmc.SERVER_JSONRPCSERVER, True)

    # Make the monitor
    monitor = ElementumMonitor()

    threads = [
        threading.Thread(target=server_thread),  # JSONRPC thread
    ]
    if not ONLY_CLIENT and PLATFORM["fork"]:
        threads.append(threading.Thread(target=elementumd_thread, args=[monitor]))  # Elementumd thread

    for t in threads:
        t.daemon = True
        t.start()

    # XBMC loop
    while not monitor.abortRequested():
        xbmc.sleep(1000)

    try:
        monitor.onAbortRequested()
    except:
        pass

    log.info("elementum: exiting elementumd")
