# -*- coding: UTF-8 -*-

__revision__ = '$Id$'

# Copyright (c) 2005-2011 Vasco Nunes, Piotr Ożarowski
#
# 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 2 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 Library General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA

# You may use and distribute this software under the terms of the
# GNU General Public License, version 2 or later

from gi.repository import Gtk
from gi.repository import GdkPixbuf
import version
import os
from pathlib import Path
import logging
from gutils import read_file
from gettext import gettext as _

log = logging.getLogger('Griffith')


def parse_translator_info(data):
    translator_credits = ""
    if data:
        for line in data.split('\n'):
            if line.startswith('* '):
                lang = line[2:]
                if _(lang) != lang:
                    line = f"* %s:" % _(lang)
            translator_credits += "%s\n" % line
    else:
        translator_credits = _("See TRANSLATORS file")
    return translator_credits


class AboutDialog:
    """Shows a gtk about dialog"""

    def __init__(self, locations):
        # FIXME: is this statement still valid since Python 3 is used:
        #  "remember to encode this file in UTF-8"
        translators_file = Path(locations['share'], 'TRANSLATORS')
        translators_default_fname = Path('/usr/share/doc/griffith/TRANSLATORS')
        gpl2_fname = Path('/usr/share/common-licenses/GPL-2')
        images_dir = locations['images']

        def _open_url(new_dialog, link):
            from . import gutils
            gutils.run_browser(link)

        # Gtk.about_dialog_set_url_hook(_open_url)

        dialog = Gtk.AboutDialog()
        dialog.set_name(version.pname)
        dialog.set_version(version.pversion)
        dialog.set_copyright(
            "Copyright © 2005-2017 Vasco Nunes. Piotr Ożarowski")
        dialog.set_website(version.pwebsite)
        dialog.set_authors([
            _("Main Authors") + ':',
            version.pauthor.replace(', ', '\n') + "\n",
            _("Programmers") + ':',
            'Jessica Katharina Parth <Jessica.K.P@women-at-work.org>',
            'Michael Jahn <mikej06@hotmail.com>',
            'Ivo Nunes <netherblood@gmail.com>',
            'John Cheetham <kaama12@yahoo.co.uk>\n',
            _('Contributors') + ':',
            'Christian Sagmueller <christian@sagmueller.net>\n'
            'Arjen Schwarz <arjen.schwarz@gmail.com>\n'
            'Joshua Gentry\n'
            'Wolfgang Friebel'
            ])
        dialog.set_artists(
            [_("Logo, icon and general artwork by Peek <peekpt@gmail.com>."
               "\nPlease visit http://www.peekmambo.com/\n"),
             'seen / unseen icons by dragonskulle <dragonskulle@gmail.com>'
             ])
        data = None
        if translators_file.is_file():
            data = read_file(translators_file)
        elif translators_file.with_suffix('.gz').is_file():
            from .gutils import decompress
            data = decompress(read_file(translators_file.with_suffix('.gz')))
        elif os.name == 'posix':
            if translators_default_fname.is_file():
                data = read_file(translators_default_fname)
            elif translators_default_fname.with_suffix('.gz').is_file():
                from .gutils import decompress
                data = decompress(
                    read_file(translators_file.with_suffix('.gz')))
        dialog.set_translator_credits(parse_translator_info(data))
        logo_file = os.path.abspath(os.path.join(images_dir, 'griffith.png'))
        logo = GdkPixbuf.Pixbuf.new_from_file(logo_file)
        dialog.set_logo(logo)
        if gpl2_fname.is_file():
            dialog.set_license(read_file(gpl2_fname))
        else:
            gpl2_site = "https://www.gnu.org/licenses/old-licenses/gpl-2.0.html"
            dialog.set_license(
                _("This program is released under the GNUGeneral Public License.\n"
                                  f"Please visit {gpl2_site} for details."))
        dialog.set_comments(version.pdescription)
        dialog.connect("response", lambda d, r: d.destroy())

        # Add TMDB attribution (required condition of using the API)
        ca = dialog.get_content_area()
        logo_file2 = os.path.abspath(os.path.join(images_dir, 'tmdb.png'))
        logo2 = GdkPixbuf.Pixbuf.new_from_file(logo_file2)
        im = Gtk.Image.new_from_pixbuf(logo2)
        im.show()
        disclaimer = ("This product uses the TMDb API\nbut is not endorsed or "
                      "certified by TMDb.")
        lbl = Gtk.Label(disclaimer)
        lbl.show()
        ca.pack_end(lbl, True, True, 0)
        ca.pack_end(im, True, True, 5)

        dialog.show()
