#! /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 random import choice

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

#Template Moduiles
from .designer.about import Ui_TemplateAbout

#Client Modules
from engine.config import * #imports METADATA
from qtgui.resources import *  #Has the logo
import engine.api as api #Already loaded, will not change anything



class About(QtWidgets.QDialog):
    """A help window with useful tips.
    Also the nagscreen for Donations.
    
    The didYouKnow sentences stay here to be edited and not in engine/constants.py?
    They are GUI only and need to be translated    
    
    The About dialog depends on a set key guiSharedDataToSave["showAboutDialog"]. That is usually
    created in the mainWindow for a new instance, never saved, and intial value depends on 
    METADATA["showAboutDialogFirstStart"]
    """

    didYouKnow = [] #Will be filled by the non-template part of the program

    def __init__(self, mainWindow):
        #super(DidYouKnow, self).__init__(parent, QtCore.Qt.WindowStaysOnTopHint|QtCore.Qt.CustomizeWindowHint|QtCore.Qt.X11BypassWindowManagerHint)
        #super(DidYouKnow, self).__init__(parent, QtCore.Qt.FramelessWindowHint)
        
        super().__init__(parent=mainWindow)        
        self.setModal(True) #block until closed
        self.ui = Ui_TemplateAbout() 
        self.ui.setupUi(self)
        self.mainWindow = mainWindow
                
        self.ui.didyouknowLabel.setText(choice(self.tricks()))
        self.index = self.tricks().index(self.ui.didyouknowLabel.text())

        self.ui.numberSlider.setMaximum(len(self.tricks())-1)
        self.ui.numberSlider.setValue(self.index)

        self.ui.numberLabel.setText("Tip " + str(self.index+1) + "/" + str(len(self.tricks())))

        self.ui.numberSlider.valueChanged.connect(self.moveSlider)
        
        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)
        self.ui.goldenratioLabel.setPixmap(aboutLogoPixmap)        

        """
        #We don't want the user to get bombarded with information on the first start. 
        #Only show us the second time.
        if not "showAboutDialog" in api.session.guiSharedDataToSave:            
            self.ui.showOnStartup.hide()            
            api.session.guiSharedDataToSave["showAboutDialog"] = True           
        """        
        
        self.ui.showOnStartup.stateChanged.connect(self.saveStartupState)        

        """
        QAbstractSlider.SliderNoAction  0
        QAbstractSlider.SliderSingleStepAdd 1
        QAbstractSlider.SliderSingleStepSub 2
        QAbstractSlider.SliderPageStepAdd   3
        QAbstractSlider.SliderPageStepSub   4
        QAbstractSlider.SliderToMinimum 5
        QAbstractSlider.SliderToMaximum 6
        QAbstractSlider.SliderMove  7
        """
        self.shortcut("right", lambda: self.ui.numberSlider.triggerAction(1))
        self.shortcut("left", lambda: self.ui.numberSlider.triggerAction(2))
        self.shortcut("up", lambda: self.ui.numberSlider.triggerAction(1))
        self.shortcut("down", lambda: self.ui.numberSlider.triggerAction(2))


        self.ui.numberSlider.wheelEvent = self.mouseWheelEventCustom #Deactivate the normal number slider wheel event
        self.wheelEvent = self.mouseWheelEventCustom #Use a window wide one that is easier to control
        
        settings = QtCore.QSettings("LaborejoSoftwareSuite", METADATA["shortName"])                               
        self.ui.showOnStartup.setChecked(settings.value("showAboutDialog", type=bool))

        self.ui.numberSlider.setFocus(True)
        

    def tricks(self):
        """For some reason translations do not work if saved as class variable.
        A getter function works"""        
        
        return About.didYouKnow +  [
            #Make the first three words matter!
            #Do not start them all with "You can..." or "...that you can", in response to the Did you know? title.
            QtCore.QCoreApplication.translate("TemplateAbout", "Help can be found through the <a href='http://laborejo.org'>Laborejo Community</a>"),
            QtCore.QCoreApplication.translate("TemplateAbout", "Temporary Shortcuts can be created by hovering the mouse cursor over a menu entry (with no shortcut) and pressing a numpad key"),        
            QtCore.QCoreApplication.translate("TemplateAbout", "Closing the program with the [X] icon or shortcuts like Alt+F4 will only hide the window. This state will be saved, so you don't need to see the window each time you load your session."),                
            ]  
    
    def reject(self):        
        self.hide()
        
    def showEvent(self, event):
        """The qt main loop is slow. We can't show the about dialog, or any other sub-dialog,
        right after mainWindow.show() becauer the event loop is not ready and the screen positions
        will be wrong.
        
        Instead we wait that the showEvent actually arrives. 
        And even then we wait a few ms, to be on the safe side. That was actually needed on the
        devs system.
        
        Also the dialog is sometimes not closed but hidden.
        Also we had reports of not correctly parented and centered dialogs. 
        
        Make sure everything is where it should be"""                        
        parentCenter = self.mainWindow.geometry().center()
        aboutCenter = self.geometry().center()        
        self.move(parentCenter - aboutCenter)
        event.accept()
    
    def mouseWheelEventCustom(self, event):        
        event.accept()        
        if event.angleDelta().y() > 0:
            self.ui.numberSlider.triggerAction(1)
        else:
            self.ui.numberSlider.triggerAction(2)

    def shortcut(self, key, function):
        act = QtWidgets.QAction('')
        act.setShortcut(key)
        act.triggered.connect(function)
        self.addAction(act)

    def saveStartupState(self):             
        settings = QtCore.QSettings("LaborejoSoftwareSuite", METADATA["shortName"])                       
        settings.setValue("showAboutDialog", bool(self.ui.showOnStartup.checkState()))        

    def moveSlider(self):
        nowIdx = self.ui.numberSlider.value()
        self.ui.didyouknowLabel.setText(self.tricks()[nowIdx])
        self.ui.numberLabel.setText("Trick " + str(nowIdx+1) + "/" + str(len(self.tricks())))
