# Window.py -- Pamhyr
# Copyright (C) 2023-2026  INRAE
#
# This program 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 <https://www.gnu.org/licenses/>.

# -*- coding: utf-8 -*-

import os
import sys
import logging
import subprocess

from PyQt5.QtCore import QUrl, QCoreApplication
from PyQt5.QtGui import QDesktopServices
from PyQt5.QtWidgets import QApplication, QWidget, QVBoxLayout, QAction
from PyQt5.QtWebEngineWidgets import QWebEngineView, QWebEngineSettings

from View.Tools.PamhyrWindow import PamhyrWindow

logger = logging.getLogger()

_translate = QCoreApplication.translate


class DocWindow(PamhyrWindow):
    _pamhyr_ui = "WebView"
    _pamhyr_name = "Documentation"

    @classmethod
    def _path_file(cls, filename):
        if ".py" in sys.argv[0]:
            return os.path.abspath(
                os.path.join(
                    os.path.dirname(__file__),
                    "..", "..", "..", "doc", filename
                )
            )

        return os.path.abspath(
            os.path.join(
                os.path.dirname(__file__),
                "..", "..", "..", "doc", filename
            )
        )

    def __init__(self, filename=None,
                 study=None, config=None,
                 parent=None):
        title = _translate("Documentation", "Documentation")
        title += f" - {filename}"

        super(DocWindow, self).__init__(
            title=title,
            study=study,
            config=config,
            options=[],
            parent=parent
        )

        self._path = self._path_file(filename)

        self.setup_web_engine()
        self.setup_url(self._path)
        self.setup_connection()

    def setup_connection(self):
        self.findChild(QAction, "action_back").triggered.connect(self.back)
        self.findChild(QAction, "action_forward").triggered.connect(
            self.forward)

        self.findChild(QAction, "action_open").triggered.connect(self.open)

    def setup_web_engine(self):
        vl = self.find(QVBoxLayout, "verticalLayout")
        self._web_view = QWebEngineView()

        settings = self._web_view.settings()
        settings.setAttribute(QWebEngineSettings.PluginsEnabled, True)
        settings.setAttribute(QWebEngineSettings.JavascriptEnabled, True)
        settings.setAttribute(QWebEngineSettings.PdfViewerEnabled, True)

        vl.addWidget(self._web_view)

    def setup_url(self, filename):
        logger.info(f"Open documentation : {filename}")
        self._web_view.setUrl(QUrl(f"file://{self._path_file(filename)}"))

    def back(self):
        self._web_view.back()

    def forward(self):
        self._web_view.forward()

    def open(self):
        url = QUrl(f"file://{self._path}")
        QDesktopServices.openUrl(url)
