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

__revision__ = '$Id$'

# Copyright (c) 2005-2009 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
import os
import subprocess
import sys
from reportlab.pdfgen import canvas
from reportlab.pdfbase import pdfmetrics
from reportlab.pdfbase.ttfonts import TTFont
from reportlab.lib import colors
import db
import gutils
import version
import logging
from gettext import gettext as _

exec_location = os.path.abspath(os.path.dirname(sys.argv[0]))
log = logging.getLogger("Griffith")


def cover_image(self, number):
    filename = gutils.file_chooser(
        _("Select image"),
        action=Gtk.FileChooserAction.OPEN,
        buttons=(Gtk.STOCK_CANCEL, Gtk.ResponseType.CANCEL,
                 Gtk.STOCK_OPEN, Gtk.ResponseType.OK))
    if filename[0]:
        cover_image_process(self, filename[0], number)


def cover_image_process(self, filename, number):
    size = self.widgets['print_cover']['ci_size'].get_active()
    print_number = self.widgets['print_cover']['ci_number'].get_active()

    if self.config.get('font', '') != '':
        font_name = "custom_font"
        pdfmetrics.registerFont(TTFont(font_name, self.config.get('font', '')))
    else:
        font_name = "Helvetica"

    if size == 0:
        # standard
        cover_x = 774
        cover_y = 518
    elif size == 1:
        # slim
        cover_x = 757
        cover_y = 518
    else:
        # double slim
        cover_x = 757
        cover_y = 518

    # A4 landscape definition
    page_width = 842
    page_height = 595

    # hardcoded to A4
    pos_x = (page_width - cover_x) / 2
    pos_y = (page_height - cover_y) / 2

    # make a pdf
    # using a truetype font with unicode support
    c = canvas.Canvas(os.path.join(self.griffith_dir, "cover.pdf"),
                      (page_width, page_height))
    c.setFont(font_name, 8)
    # copyright line
    c.drawString(
        20, 20,
        _("Cover generated by Griffith v") +
        version.pversion + " (C) 2004-2009 Vasco Nunes/Piotr Ozarowski - " +
        _("Released Under the GNU/GPL License"))

    # get movie information from db
    movie = self.db.session.query(db.Movie).filter_by(number=number).first()
    if movie is not None:
        c.drawImage(filename, pos_x, pos_y, cover_x, cover_y)
        if print_number:
            c.setFillColor(colors.white)
            c.rect((page_width / 2) - 13, 520, 26, 70, fill=1, stroke=0)
            c.setFillColor(colors.black)
            c.setFont(font_name, 10)
            c.drawCentredString(page_width / 2, 530, number)

    # draw cover area
    c.rect(pos_x, pos_y, cover_x, cover_y)

    c.showPage()
    c.save()
    self.widgets['print_cover']['window_simple'].hide()
    cover_file = os.path.join(self.griffith_dir, "cover.pdf")
    if self.windows:
        os.popen3("\"" + cover_file + "\"")
    else:
        try:
            subprocess.Popen([self.pdf_reader, cover_file])
        except FileNotFoundError as fnfe:
            log.warning(f"{self.pdf_reader} not installed, error: '{fnfe}")


def cover_simple(self, number):
    size = self.widgets['print_cover']['cs_size'].get_active()
    print_number = self.widgets['print_cover']['cs_include_movie_number'].get_active()
    poster = self.widgets['print_cover']['cs_include_poster'].get_active()

    if self.config.get('font', '') != '':
        font_name = "custom_font"
        pdfmetrics.registerFont(TTFont(font_name, self.config.get('font', '')))
    else:
        font_name = "Helvetica"

    if size == 0:
        # standard
        cover_x = 774
        cover_y = 518
    elif size == 1:
        # slim
        cover_x = 757
        cover_y = 518
    else:
        # double slim
        cover_x = 757
        cover_y = 518

    # A4 landscape definition
    page_width = 842
    page_height = 595

    # hardcoded to A4
    pos_x = (page_width - cover_x) / 2
    pos_y = (page_height - cover_y) / 2
    # make a pdf
    c = canvas.Canvas(os.path.join(self.griffith_dir, "cover.pdf"),
                      (page_width, page_height))
    c.setFont(font_name, 8)

    # copyright line
    c.drawString(
        20, 20,
        _("Cover generated by Griffith v") + version.pversion +
        " (C) 2004-2009 Vasco Nunes/Piotr Ozarowski - " +
        _("Released Under the GNU/GPL License"))

    # draw cover area
    c.rect(pos_x, pos_y, cover_x, cover_y)

    # get movie information from db
    movie = self.db.session.query(db.Movie).filter_by(number=number).first()
    if movie is not None:
        if print_number:
            c.setFont(font_name, 10)
            c.drawCentredString(page_width / 2, 530, number)

        c.setFont(font_name, 16)
        c.rotate(90)
        c.drawString(60, (-page_width / 2) - 8, movie.o_title.encode('utf-8'))
        c.rotate(-90)
        filename = ''
        if movie.poster_md5:
            filename = gutils.get_image_fname(movie.poster_md5, self.db)
            if filename:
                c.drawImage(filename, x=(page_width - 30) / 2, y=470, width=30,
                            height=50)
        # print movie info
        c.setFont(font_name, 8)
        text_object = c.beginText()
        text_object.setTextOrigin(page_width - cover_x, 300)
        text_object.setFont(font_name, 8)
        text_object.textLine("%s: %s" % (_('Original Title'), movie.o_title))
        text_object.textLine("%s: %s" % (_('Title'), movie.title))
        text_object.textLine('')
        text_object.textLine("%s: %s" % (_('Director'), movie.director))
        text_object.textLine('')
        text_object.textLine("%s: %s %s" % (_('Running Time'), movie.runtime,
                                            _(' min')))
        text_object.textLine("%s: %s" % (_('Country'), movie.country))
        text_object.textLine("%s: %s" % (_('Genre'), movie.genre))
        text_object.textLine('')
        c.drawText(text_object)
        # draw bigger poster image
        if poster and movie.poster_md5 and filename:
            c.drawImage(
                filename, x=(page_width - (page_width - cover_x) - 235),
                y=(page_height / 2) - 125, width=180, height=250)
    c.showPage()
    c.save()
    self.widgets['print_cover']['window_simple'].hide()
    cover_file = os.path.join(self.griffith_dir, 'cover.pdf')
    if self.windows:
        os.popen3("\"" + cover_file + "\"")
    elif self.mac:
        os.popen3("open -a Preview" + " " + cover_file)
    else:
        try:
            subprocess.Popen([self.pdf_reader, cover_file])
        except FileNotFoundError as fnfe:
            log.warning(f"{self.pdf_reader} not installed, error: '{fnfe}'")
