#!/usr/bin/python3 -u


import dbus, dbus.service, dbus.exceptions
import dbus.mainloop.glib
import json
import os
import sys
import time

from gi.repository import GLib
from os.path import expanduser
global install_path
install_path = os.path.abspath(f"{sys.path[0]}/..")
sys.path.insert(1, f"{install_path}/lib/python3/dist-packages")

import auto_jack
global name_base
global control_interface_name
global configure_interface_name
global service_name
name_base = 'org.jackaudio'
control_interface_name = name_base + '.JackControl'
configure_interface_name = name_base + '.Configure'
service_name = name_base + '.service'

class sendbus(dbus.service.Object):
    def __init__(self):
        dbus.service.Object.__init__(self, dbus.SessionBus(), "/")

    @dbus.service.signal(dbus_interface="org.studio.control.command", signature="s")
    def signal(self, sg):
        pass


def set_db(jack):
    global conf_db
    c_file = expanduser(auto_jack.new_name)
    print(c_file)
    if not os.path.isfile(c_file):
        sys.exit("Configuration file not created, Please run Studio Controls first")
    # config file exists, read it in no_check = True
    # (autojack should have already done that)
    auto_jack.log = False
    auto_jack.check_new(True)
    auto_jack.our_db['jack']['on'] = jack
    auto_jack.write_new()
    time.sleep(.5)


def goodbye(dummy):
    """ This is because we have to run a mainloop to send dbus
        messages so we wait some time to allow message to be sent
        and then this is called to exit the mainloop
    """
    sys.exit()


def main(argv):
    ''' Control-cmd takes either start or stop as a command line
        parameter to send to auto jack '''
    dbus.mainloop.glib.DBusGMainLoop(set_as_default=True)
    sendbs = sendbus()
    if len(sys.argv) == 2:
        command = sys.argv[1]
        if command == "start":
            # idea to think on:
            # ping and check autojack version to restart if not current
            jack = True
            set_db(jack)
            sendbs.signal(command)
        elif command == "stop":
            jack = False
            set_db(jack)
            sendbs.signal(command)
        elif command == "phones" or command == "monitor":
            sendbs.signal(command)
        else:
            print("invalid argument")
            sys.exit(2)
    else:
        print("invalid argument")
        sys.exit(2)

    timeout_id = GLib.timeout_add(100, goodbye, None)

    loop = GLib.MainLoop()
    loop.run()

if __name__ == '__main__':
    main(sys.argv[1:])
