import sys
from pathlib import Path

import wx

from clarabot_nano import __version__
from clarabot_nano.common.i18n import DETECTED_SYSTEM_LANGUAGE
from clarabot_nano.control.icon import get_wx_nano_icon
from clarabot_nano.control.utility import change_font_to_bold


class AboutDialog(wx.Dialog):
    @classmethod
    def read_license(cls) -> str:
        languages = []
        if DETECTED_SYSTEM_LANGUAGE:
            languages.append("_" + DETECTED_SYSTEM_LANGUAGE)
        languages.append("_en")  # fallback is English
        try:
            exe_dir = Path(sys.executable).parent
            for lang in languages:
                lang_path = exe_dir / f"LICENSE{lang.upper()}.txt"
                if lang_path.is_file():
                    return lang_path.read_text(encoding="utf-8-sig")
        except OSError:
            pass
        return "Clarabot Nano\nCopyright (c) 2021 Clarabot Zrt.\n\nCould not load detailed license."

    @classmethod
    def read_used_legal(cls) -> str:
        try:
            third_party_text = (Path(sys.executable).parent / "THIRDPARTYSOFTWARE.txt").read_text(encoding="utf-8")
        except OSError:
            third_party_text = "Could not load legal information of third-party software."
        return third_party_text

    def __init__(self, parent):
        wx.Dialog.__init__(self, parent, wx.ID_ANY, gettext("About"), style=wx.DEFAULT_DIALOG_STYLE | wx.RESIZE_BORDER)
        self.SetSizeHints(320, 320)
        self.SetIcon(get_wx_nano_icon())
        self.SetSize(600, 400)

        layout = wx.BoxSizer(wx.VERTICAL)
        self._title_label = wx.StaticText(self, wx.ID_ANY, f"Clarabot Nano {__version__}")
        change_font_to_bold(self._title_label)
        layout.Add(self._title_label, 0, wx.ALL | wx.EXPAND, 8)

        self._tabs = wx.Notebook(self)
        layout.Add(self._tabs, 1, wx.LEFT | wx.RIGHT | wx.BOTTOM | wx.EXPAND, 16)

        # NOTE: TE_RICH is MSW-specific to allow longer value than 64K characters.
        _long_text_ctrl_style = wx.TE_RICH | wx.TE_MULTILINE | wx.TE_READONLY

        self._license_text = wx.TextCtrl(
            self._tabs, wx.ID_ANY, self.read_license(), style=_long_text_ctrl_style | wx.TE_WORDWRAP | wx.TE_AUTO_URL
        )
        self._tabs.AddPage(self._license_text, "License")
        self.Bind(wx.EVT_TEXT_URL, self._on_url, self._license_text)

        self._used_text = wx.TextCtrl(
            self._tabs, wx.ID_ANY, self.read_used_legal(), style=_long_text_ctrl_style | wx.TE_DONTWRAP
        )
        self._tabs.AddPage(self._used_text, "Used software")

        buttons = self.CreateButtonSizer(wx.OK)
        if buttons:
            layout.Add(buttons, 0, wx.LEFT | wx.RIGHT | wx.BOTTOM | wx.EXPAND, 8)

        self.SetSizer(layout)

    def _on_url(self, evt):
        url = self._license_text.GetValue()[evt.GetURLStart() : evt.GetURLEnd()]
        mouse = evt.GetMouseEvent()
        # NOTE: There is no "Up" event on Windows here.
        if mouse.LeftDown():
            wx.LaunchDefaultBrowser(url)
