"""

    [App documentation here]

    @author:[author], [year]
"""

import sys

import yaml
from PyQt5.Qt import QApplication
from PyQt5.QtWidgets import QMessageBox

from core import db
from core.constants import SETTING_PATH, SETTING_DIST_PATH
from core.indexer import Indexer
from core.logging_ import Logger
from ui.window import MainWindow

try:
    # Necessary to ensure that stacktraces are printed when using PyQt5
    # Tough, could make pythonw.exe crash
    import ipdb  # @UnusedImport
except:
    pass

logger = Logger.get()

main_window = None

# Configure how errors are processed
sys_err = sys.excepthook
def err_handler(typ, value, trace):
    QApplication.restoreOverrideCursor()
    if main_window:
        QMessageBox.critical(main_window, "Erreur: {}".format(typ.__name__), """{}""".format(value))
    sys_err(typ, value, trace)
sys.excepthook = err_handler

# create settings file
if not SETTING_PATH.exists():
    SETTING_DIST_PATH.copy(SETTING_PATH)

settings = yaml.load(SETTING_PATH.text(), Loader=yaml.FullLoader)

# Create db if not existing
try:
    db.create()
except FileExistsError:
    pass

# Start UI
logger.info("-- Start --")
app = QApplication(sys.argv)
indexer = Indexer()
indexer.start()
main_window = MainWindow(settings)

# connect indexer signals
indexer.emitter.filesIndexed.connect(main_window.filesIndexed)
indexer.emitter.musicFolderStatusChanged.connect(main_window.musicFolderStatusChanged)


main_window.show()

try:
    r = app.exec_()
finally:
    indexer.stop()
    try:
        settings = main_window.currentSettings()
        with open(SETTING_PATH, 'w') as f:
            yaml.dump(settings, f)
    finally:
        db.close()

logger.info("-- Closed --")
sys.exit(r)

