#! /usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Copyright 2021, Nils Hilbricht, Germany ( https://www.hilbricht.net )

This file is part of the Laborejo Software Suite ( https://www.laborejo.org ),

This application is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program.  If not, see <http://www.gnu.org/licenses/>.
"""

import logging; logger = logging.getLogger(__name__); logger.info("import")


#Standard Lib
from tempfile import gettempdir
from pathlib import Path
import os.path
from os import makedirs

#System Wide Modules
from PyQt5 import QtCore, QtWidgets, QtGui

#Template Moduiles
from .designer.chooseSessionDirectory import Ui_TemplateChooseSessionDirectory
from .resources import * #has the translation

#Client Modules
from engine.config import * #imports METADATA
from qtgui.resources import *  #Has the logo


class ChooseSessionDirectory(QtWidgets.QDialog):
    def __init__(self, qtApp):

        language = QtCore.QLocale().languageToString(QtCore.QLocale().language())
        logger.info("{}: Language set to {}".format(METADATA["name"], language))
        if language in METADATA["supportedLanguages"]:
            templateTranslator = QtCore.QTranslator()
            templateTranslator.load(METADATA["supportedLanguages"][language], ":/template/translations/") #colon to make it a resource URL
            qtApp.installTranslator(templateTranslator)

        super().__init__() #no parent, this is the top level window at this time.
        self.qtApp = qtApp
        self.setModal(True) #block until closed
        self.ui = Ui_TemplateChooseSessionDirectory()
        self.ui.setupUi(self)

        copyright = f"""{METADATA["author"]} ({METADATA["year"]})"""
        name = f"""{METADATA["name"]} ver. {METADATA["version"]}"""
        aboutText = "\n".join([name, copyright ,METADATA["url"]])
        self.ui.aboutLabel.setText(aboutText)

        #Image: 300x151
        aboutLogoPixmap = QtGui.QPixmap(":aboutlogo.png")
        pixmap_scaled = aboutLogoPixmap.scaled(self.ui.goldenratioLabel.size(), QtCore.Qt.KeepAspectRatio)
        self.ui.goldenratioLabel.setPixmap(pixmap_scaled)

        message = QtCore.QCoreApplication.translate("TemplateChooseSessionDirectory", "Please choose a directory for your session files. It is recommended to start through Agordejo/New Session Manager instead.")
        self.ui.label.setText(message)

        settings = QtCore.QSettings("LaborejoSoftwareSuite", METADATA["shortName"])
        self.recentDirList = []
        if settings.contains("recentDirectoriesWithouNSM"):
            self.recentDirList = settings.value("recentDirectoriesWithouNSM", type=list)[-5:]
            #remember self.recentDirList for later saving
            self.ui.pathComboBox.insertItems(0, reversed(self.recentDirList))
        else:
            self.ui.pathComboBox.setCurrentText(gettempdir())

        self.ui.buttonBox.accepted.connect(self.accept)
        self.ui.buttonBox.rejected.connect(self.reject)

        self.ui.openFileDialogButton.setText("")
        self.ui.openFileDialogButton.setIcon(self.style().standardIcon(getattr(QtWidgets.QStyle, "SP_DialogOpenButton")))
        self.ui.openFileDialogButton.clicked.connect(self.requestPathFromDialog)
        self.exec()


    def requestPathFromDialog(self):
        if self.ui.pathComboBox.currentText() == gettempdir():
            startPath = str(Path.home())
        else:
            startPath = self.ui.pathComboBox.currentText()
        dirname = QtWidgets.QFileDialog.getExistingDirectory(self, QtCore.QCoreApplication.translate("TemplateChooseSessionDirectory", "Choose Session Directory"), startPath)

        if dirname:
            self.ui.pathComboBox.setCurrentText(dirname)

    def accept(self):
        self.path = self.ui.pathComboBox.currentText()   #easy abstraction so that the caller does not need to know our widget name
        settings = QtCore.QSettings("LaborejoSoftwareSuite", METADATA["shortName"])
        if not os.path.exists(self.path):
            try:
                makedirs(self.path)
            except:
                pass #file saving error logging is handled later

        #There is no guarantee that the dir really exists. but at this point the user is on its own.
        #It is allowed to use /dev/null after all

        if not self.path in self.recentDirList:
            self.recentDirList.append(self.path)
        settings.setValue("recentDirectoriesWithouNSM", self.recentDirList)
        super().accept()

    def reject(self):
        self.path = None
        super().reject()

