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

__revision__ = '$Id$'

# Copyright (c) 2005-2007 Vasco Nunes
#
# 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

import csv
from gi.repository import Gtk
import os
import gutils
from plugins.export import Base
from gettext import gettext as _
import logging

log = logging.getLogger('Griffith')


class ExportPlugin(Base):
    name = "CSV"
    description = _("Full CSV list export plugin")
    author = "Vasco Nunes, Andreas Flöter"
    email = "<vasco.m.nunes@gmail.com>"
    version = "0.4"

    fields_to_export = (
        'number', 'o_title', 'title', 'director', 'year', 'classification',
        'country', 'genre', 'rating', 'runtime', 'studio', 'seen', 'loaned',
        'o_site', 'site', 'trailer', 'plot', 'cast', 'notes', 'image',
        'volumes.name', 'collections.name', 'media.name', 'screenplay',
        'cameraman', 'barcode', 'color', 'cond', 'layers', 'region',
        'media_num', 'vcodecs.name')

    def _query_filename(self, basedir: str) -> tuple[bool, str]:
        create_csv_file = False
        filename_path = None
        if not basedir:
            basedir = '~'
        filename_info = gutils.file_chooser(
            _("Export a CSV document"), action=Gtk.FileChooserAction.SAVE,
            buttons=(Gtk.STOCK_CANCEL, Gtk.ResponseType.CANCEL,
                     Gtk.STOCK_SAVE, Gtk.ResponseType.OK),
            name='griffith_list.csv', folder=basedir)
        if filename_info and filename_info[0]:
            filename_path, base_dir = filename_info
            if self.config is not None and base_dir:
                self.config.set('export_dir', base_dir, section='export-csv')
                self.config.save()
            create_csv_file = True
            if os.path.isfile(filename_path):
                if gutils.question(
                        _("File exists. Do you want to overwrite it?"),
                        self.parent_window):
                    create_csv_file = True
                else:
                    create_csv_file = False
        return create_csv_file, filename_path

    def run(self):
        if self.config is not None:
            basedir = self.config.get('export_dir', None, section='export-csv')
            create_csv, filename = self._query_filename(basedir)
            if create_csv:
                movies = self.db.session.execute(self.get_query())
                with open(filename, 'w') as csvfile:
                    writer = csv.writer(csvfile, dialect=csv.excel)
                    # write column header row
                    writer.writerow(self.fields_to_export)
                    # write data rows
                    for movie in movies:
                        writer.writerow(movie)
                gutils.info(_("CSV file has been created."),
                            self.parent_window)
