#! /usr/bin/env python3
# -*- coding: utf-8 -*-
if __name__ == "__main__":
    import argparse, sys, os
    parser = argparse.ArgumentParser(description="Laborejo Qt")
    parser.add_argument('infiles', help="One or more lbjs or lbj files to load.", nargs="*")
    parser.add_argument("-n", "--new", help="Start with an empty file (additionally to loaded files)", action="store_true")
    parser.add_argument("-c", "--config", help="The configuration dir for user scripts, templates and configs etc. Default=~/.laborejo/", type=str)
    args = parser.parse_args()

    import laborejoqt #initialize the GUI. We do this after parse init because if it were just --help we don't need to start the whole Qt chain.

    if args.config:
        p = os.path.realpath(args.config) + "/"
        print ("Starting Laborejo-Qt with config directory", p)
        laborejoqt.api._getSession().configdir = p

    laborejoqt.main = laborejoqt.StartQT4()
    laborejoqt.listener.main = laborejoqt.main

    laborejoqt.api.STANDALONE = False #Switch backend into slave mode.
    laborejoqt.api.l_global = laborejoqt.listener.ListenerGlobal()
    laborejoqt.api.l_cursor = laborejoqt.listener.ListenerCursor()
    laborejoqt.api.l_item = laborejoqt.listener.ListenerItem()
    laborejoqt.api.l_track = laborejoqt.listener.ListenerTrack()
    laborejoqt.api.l_movement = laborejoqt.listener.ListenerMovement()
    laborejoqt.api.l_form = laborejoqt.listener.ListenerFormGenerator()
    laborejoqt.api.l_chord = laborejoqt.listener.ListenerChord()
    laborejoqt.api.l_note = laborejoqt.listener.ListenerNote()


   #load command line files. A new empty file can also be opened, does not conflict with loading files.
    if args.infiles:
        for f in args.infiles:
            laborejoqt.main.load(f)
    if args.new:
        laborejoqt.api.new()
    #else it is just an empty program start

    def startAndEnd():
        if laborejoqt.config.JACK_MIDI_IN:
                midiInfunction = laborejoqt.api.jackMidiInStart() #returns the midi in processing function or None if jack was not found or server not running
                if midiInfunction:
                    midiInTimer = laborejoqt.QtCore.QTimer()
                    laborejoqt.QtCore.QObject.connect(midiInTimer, laborejoqt.QtCore.SIGNAL("timeout()"), laborejoqt.api.jackclient.midiInChooser)
                    midiInTimer.start(laborejoqt.config.MIDI_TIMER) #100ms
                #Warning messages are done by the api and jackclient

        laborejoqt.main.ui.actionMIDI_Note_Entry.setChecked(True) #Display bugfix. The checked goes away after starting.
        laborejoqt.app.exec_()
        if laborejoqt.config.JACK_MIDI_IN:
            try:
                laborejoqt.api.jackMidiInClose()
            except:
                pass

    sys.exit(startAndEnd())
