#!/usr/bin/python3
import sys
import argparse
import platform

from PyQt5.QtWidgets import QApplication
from PyQt5.QtCore import QSettings
from PyQt5.QtGui import QIcon

from nixview.ui.mainwindow import NixView
import nixview.info as info
import resources_rc  # needs to be imported somewhere in the project to be picked up by qt compiled by ``pyrcc5 -o resources_rc.py resources.qrc``


if platform.system() == "Windows":
    from PyQt5.QtWinExtras import QtWin
    myappid = "%s.%s" %(info.ORGANIZATION, info.VERSION)
    QtWin.setCurrentProcessExplicitAppUserModelID(myappid)


def main():
    parser = argparse.ArgumentParser(description="NixView. Viewer for NIX data files. For more on nix see https://nixio.readthedocs.io/en/master")
    parser.add_argument("file", nargs="?", default="", type=str, help="The nix file that should be opened.")
    args = parser.parse_args()
    app = QApplication(sys.argv)
    app.setApplicationName(info.NAME)
    app.setApplicationVersion(str(info.VERSION))
    app.setOrganizationDomain(info.ORGANIZATION)
    if platform.system() == 'Linux':
        app.setWindowIcon(QIcon(":/icons/app_icon_png"))
    
    settings = QSettings(info.ORGANIZATION, info.NAME)
    width = int(settings.value("app/width", 1024))
    height = int(settings.value("app/height", 768))
    x = int(settings.value("app/pos_x", 100))
    y = int(settings.value("app/pos_y", 100))
    
    window = NixView()
    window.setMinimumWidth(800)
    window.setMinimumHeight(600)
    window.resize(width, height)
    window.move(x, y)
    if len(args.file.strip()) > 0:
        window.open_file(args.file)
    window.show()

    exit_code = app.exec_()

    pos = window.pos()
    settings.setValue("app/width", window.width())
    settings.setValue("app/height", window.height())
    settings.setValue("app/pos_x", pos.x())
    settings.setValue("app/pos_y", pos.y())
    sys.exit(exit_code)


if __name__ == "__main__":
    main()
