#  Copyright (c) 2025  Jeffrey Hsu - JITToolBox
#  #
#  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/>.


from PySide6.QtGui import QDesktopServices, Qt, QColor
from PySide6.QtWidgets import QVBoxLayout, QHBoxLayout, QWidget
from qfluentwidgets import FluentIcon, GroupHeaderCardWidget, PushButton, ImageLabel, \
    TitleLabel, HeaderCardWidget, BodyLabel, HyperlinkLabel, SingleDirectionScrollArea
from qfluentwidgets.components.widgets.card_widget import CardSeparator

from module.about.schema import ThirdParty
from ui.components.widget import Widget
from utils.function import RELEASE_ENV

if RELEASE_ENV:
    from build_info import *


class AboutCard(HeaderCardWidget):
    def __init__(self, parent=None):
        super().__init__(parent)
        self.setTitle('关于本程序')

        self.vBoxLayout = QVBoxLayout(self)
        self.vBoxLayout.setContentsMargins(0, 0, 0, 0)
        self.lineHBoxLayout = QHBoxLayout(self)
        self.lineHBoxLayout.setContentsMargins(24, 16, 24, 8)
        self.lineVBoxLayout = QVBoxLayout(self)
        self.lineVBoxLayout.setContentsMargins(0, 0, 0, 0)
        self.textVBoxLayout = QVBoxLayout(self)
        self.textVBoxLayout.setContentsMargins(24, 8, 24, 16)
        self.viewLayout.setContentsMargins(0, 0, 0, 0)
        self.gplv3Image = ImageLabel(':/images/gplv3.png')
        self.lineHBoxLayout.addLayout(self.lineVBoxLayout)
        self.lineHBoxLayout.addWidget(self.gplv3Image)

        self.addLine('程序名称', '教学工具箱')
        if RELEASE_ENV:
            self.addLine('程序版本', '1.0.0#' + GIT_HASH)
        self.addLine('作者', '许方杰')
        if RELEASE_ENV:
            self.addLine('构建时间', BUILD_TIME)
        self.addLine('许可证', 'GNU 通用公共许可证 第三版（GPLv3）')
        self.addLineUseLink('项目主页', 'https://cantyonion.site/git/cantyonion/JITToolBox')

        self.addText(
            '教学工具箱是自由软件；您可以依据自由软件基金会发布的 GNU 通用公共许可证第三版条款，重新发布或修改它；许可证应使用第三版或（按您的选择）任何其更新的版本。')
        self.addText(
            '教学工具箱是以希望它有用为目的而发布的，但不附带任何担保；甚至没有适销性或特定用途适用性的隐含担保。请参看 GNU GPL 第三版了解更详细的内容。')
        self.addTextWithLink('您应该已收到一份 GNU 通用公共许可证的副本；如果没有，请查看<',
                             'https://www.gnu.org/licenses/gpl-3.0.html')

        self.vBoxLayout.addLayout(self.lineHBoxLayout)
        self.vBoxLayout.addWidget(CardSeparator(self))
        self.vBoxLayout.addLayout(self.textVBoxLayout)
        self.viewLayout.addLayout(self.vBoxLayout)

    def addLine(self, title: str, content: str):
        hBox = QHBoxLayout(self)
        mTitlte = BodyLabel(title, self)
        mContent = BodyLabel(content, self)
        mContent.setTextColor(QColor(96, 96, 96), QColor(206, 206, 206))
        mTitlte.setFixedWidth(100)

        hBox.addWidget(mTitlte)
        hBox.addWidget(mContent)

        self.lineVBoxLayout.addLayout(hBox)

    def addLineUseLink(self, title: str, content: str):
        hBox = QHBoxLayout(self)
        mTitle = BodyLabel(title, self)
        mContent = HyperlinkLabel(content, content)
        mTitle.setFixedWidth(100)

        hBox.addWidget(mTitle)
        hBox.addWidget(mContent)

        self.lineVBoxLayout.addLayout(hBox)
        mContent.clicked.connect(lambda: QDesktopServices.openUrl(content))

    def addText(self, text: str):
        label = BodyLabel(text, self)
        label.setWordWrap(True)
        self.textVBoxLayout.addWidget(label)

    def addLink(self, text: str, url: str):
        link = HyperlinkLabel(url, text)
        link.setUrl(url)
        self.textVBoxLayout.addWidget(link)

    def addTextWithLink(self, text: str, url: str):
        hBox = QHBoxLayout(self)
        label = BodyLabel(text, self)
        link = HyperlinkLabel(url, url)
        link.setContentsMargins(0, 0, 0, 0)
        hBox.addWidget(label)
        hBox.addWidget(link)
        hBox.addWidget(BodyLabel(">。", self))
        self.textVBoxLayout.addLayout(hBox)
        link.clicked.connect(lambda: QDesktopServices.openUrl(url))


class AboutMain(QWidget):
    def __init__(self, parent=None):
        super().__init__(parent)

        self.logoImage = ImageLabel(':/images/logo.png')
        self.logoImage.scaledToHeight(100)
        self.appNameLabel = TitleLabel('教学工具箱 🛠️')

        self.hBox = QHBoxLayout()
        self.hBox.addWidget(self.logoImage, 0, Qt.AlignLeft)
        self.hBox.addWidget(self.appNameLabel, 1, Qt.AlignLeft)

        third_parties = [
            ThirdParty("PySide6", "https://qt.io", ":/images/3rd/qt.png"),
            ThirdParty("QFluentWidgets", "https://qfluentwidgets.com", ":/images/3rd/qfluentwidgets.png"),
            ThirdParty("openpyxl", "https://openpyxl.readthedocs.io/en/stable"),
            ThirdParty("python-docx", "https://github.com/python-openxml/python-docx"),
            ThirdParty("Matplotlib", "https://matplotlib.org", ":/images/3rd/matplotlib.svg"),
            ThirdParty("packaging", "https://github.com/pypa/packaging", ":/images/3rd/packaging.png"),
            ThirdParty("pywin32", "https://github.com/mhammond/pywin32")
        ]
        third_parties.sort(key=lambda item: item.name.lower())

        self.group_card = GroupHeaderCardWidget(self)
        self.group_card.setTitle("第三方框架")
        self.vbox = QVBoxLayout(self)

        self.vbox.addLayout(self.hBox)
        self.vbox.addWidget(AboutCard(self))
        self.vbox.addWidget(self.group_card)
        self.vbox.addStretch(1)

        [self.addThirdParty(x) for x in third_parties]

    def addThirdParty(self, third_party: ThirdParty):
        button = PushButton(FluentIcon.LINK, "访问网站")
        button.setFixedWidth(120)
        self.group_card.addGroup(third_party.qrc if third_party.qrc else FluentIcon.LAYOUT, third_party.name,
                                 third_party.url, button)
        button.clicked.connect(lambda: QDesktopServices.openUrl(third_party.url))


class AboutWidget(Widget):
    def __init__(self, key: str, parent=None):
        super().__init__(key, parent)

        self.scrollArea = SingleDirectionScrollArea(orient=Qt.Vertical)
        self.scrollArea.setWidget(AboutMain(self))
        self.scrollArea.setWidgetResizable(True)
        self.scrollArea.enableTransparentBackground()

        self.vBox = QVBoxLayout(self)
        self.vBox.setContentsMargins(0, 0, 0, 0)
        self.vBox.setSpacing(0)
        self.vBox.addWidget(self.scrollArea)
