#! /usr/bin/env python3
# -*- coding: utf-8 -*-
if __name__ == "__main__":
    import argparse, os, atexit
    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)
    parser.add_argument("-g", "--geometry", help="Start with a window geometry 'width x height' or 'width x height + leftCorner + rightCorner'. Example A: 1024x768 Example B: 1920x1080+0+0", type=str, default=None)
    parser.add_argument("-m", "--mute", help ="Don't start the audio/midi engine. You need this for playback but it can be turned off if you don't want JACK or for performance reasons", action="store_true")
    parser.add_argument("-j", "--jack", help ="Start with active JACK Mode instead of internal sampler mode. Can be toggled at any time in the program again.", action="store_true")
    parser.add_argument("-i", "--midiin", help="Jack Midi input port for note insert. No ALSA. Example: jack-keyboad:midi_out . Default: as sepcified in config file.", type=str, default=None)
    parser.add_argument("-e", "--session", help ="Session Manager Mode. Don't connect any jack ports except the internal sampler.", action="store_true")
    parser.add_argument("-s", "--soundfont", help="A path to an alternative .sf2 soundfont to be used by the internal midi sampler. Example /usr/share/soundfonts/fluidr3/FluidR3GM.SF2", type=str, default=None)


    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.config.JACKMODE = args.jack

    laborejoqt.main = laborejoqt.StartQT4(geometry = args.geometry)

    if laborejoqt.config.JACK and not args.mute:
        midiInPort = args.midiin if args.midiin else laborejoqt.config.midiinport
        laborejoqt.api.calfboxInit(args.soundfont, autoconnect=not args.session, midiInPort = midiInPort) #If soundfont is none it falls back to a small default GM provided within the Laborejo source tree

    if laborejoqt.api.cboxSmfCompatibleModule: #started succesfully?
        laborejoqt.main.session.playbackEngine = True
        midiInTimer = laborejoqt.QtCore.QTimer()
        laborejoqt.QtCore.QObject.connect(midiInTimer, laborejoqt.QtCore.SIGNAL("timeout()"), laborejoqt.api.midiInProcessor)
        midiInTimer.start(laborejoqt.config.MIDI_TIMER) #50ms
    else:
        laborejoqt.main.session.playbackEngine = False

    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_score = laborejoqt.listener.ListenerScore()
    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:
        lbjsScoreFiles = [x for x in args.infiles if x.endswith(".lbjs")]
        lbjCollectionFiles = [x for x in args.infiles if x.endswith(".lbj")]
        if lbjsScoreFiles:
            laborejoqt.main.load(lbjsScoreFiles)
        if lbjCollectionFiles:
            laborejoqt.main.loadCollection(lbjCollectionFiles)

    if args.new:
        laborejoqt.api.new()
    #else it is just an empty program start

    atexit.register(laborejoqt.api.calfboxShutdown) #On Exit shut down the jack client properly. Even if started with -m this will not fail. There is a "try" inside.

    laborejoqt.app.exec_()
