# Copyright (C) 2008-2009 LottaNZB Development Team
# 
# 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; version 3.
# 
# 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, write to the Free Software
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA.

import gtk
import pango
import gobject

from os.path import dirname, join

from kiwi.ui.objectlist import Column
from kiwi.python import Settable

from lottanzb.util import gproperty, _
from lottanzb.plugins import PluginBase, PluginConfig, PluginPrefsTabBase
from lottanzb.modes import standalone

class Config(PluginConfig):
    def __init__(self, *args, **kwargs):
        PluginConfig.__init__(self, *args, **kwargs)
        
        if not self.categories_list:
            self.categories_list = [
                _("Music"),
                _("DVD Movie"),
                _("XVID Movie"),
                _("TV Series"),
                _("HD Movie"),
                _("Game"),
                _("Software"),
                _("Other")
            ]
    
    categories_list = gproperty(type=object)
    
    # It's a good idea not to change this option. The way how LottaNZB saves
    # a download category might change in the future so that we won't need
    # this option anymore.
    separator = gproperty(type=str, default="--")

class Plugin(PluginBase):
    title = _("Categorization")
    description = _("Use categories to group completed downloads in the "
        "download directory.")
    author = _("LottaNZB Development Team")
    requires_modes = [standalone.Mode]
    
    def refresh(self):
        hella_config = self.app.mode_manager.current_hella_config
        
        if hella_config:
            # Hackish solution, but this is code will be dropped in the next
            # version of the application anyway.
            script = join(dirname(__file__), "postprocessor.py")
            hella_config.external_handler_script = script
    
    def extend_add_dialog(self, main_window, dialog):
        category_widget = gtk.combo_box_new_text()
        
        for category in self.config.categories_list:
            category_widget.append_text(category)
        
        category_widget.set_active(len(self.config.categories_list) - 1)
        
        def name_lambda(name):
            separator = self.config.separator
            category = category_widget.get_active_text()
            
            return "%s%s%s" % (category, separator, name)
        
        dialog.add_option(_("Category:"), category_widget)
        dialog.name_lambdas.append(name_lambda)
    
    def extend_newzbin_dialog(self, plugin, dialog):
        def name_lambda(name, downloader):
            separator = self.config.separator
            category = downloader.category
            
            return "%s%s%s" % (category, separator, name)
        
        dialog.name_lambdas.append(name_lambda)
    
    def on_main_window_ready(self, main_window):
        self.connect_when_enabled(
            main_window,
            "add-file-dialog-opened",
            self.extend_add_dialog
        )
        
        newzbin_plugin = self.app.plugin_manager.plugins.get("newzbin", None)
        
        if newzbin_plugin:
            self.connect_when_enabled(
                newzbin_plugin,
                "add-dialog-opened",
                self.extend_newzbin_dialog
            )
        
        column = Column("category", title=_("Category"), expand=True)
        
        self.insert_download_list_column(column, 1)
        self.refresh()

class PrefsTab(PluginPrefsTabBase):
    gladefile = "plugin_categories_prefs_tab"
    label = _("Categories")
    creation_row = None
    creation_hint = _("Add a new category...")
    
    def __init__(self, prefs_window, plugin):
        PluginPrefsTabBase.__init__(self, prefs_window, plugin)
        
        self.categories_column = CategoryColumn(self.creation_hint)
        self.categories_list.set_columns([self.categories_column]) 
        
        renderer = self.categories_column.renderer
        renderer.connect("editing-started", self.on_editing_started)
        
        self.add_creation_cell()
        
        for category in self.plugin.config.categories_list:
            self.categories_list.append(Settable(category=category))
    
    def add_creation_cell(self):
        self.creation_row = Settable(category=self.creation_hint)
        self.categories_list.insert(0, self.creation_row)
    
    def on_categories_list__cell_edited(self, widget, category_row, event):
        category = category_row.category
        
        if category_row is self.creation_row:
            if not category:
                category_row.category = self.creation_hint
                widget.update(category_row)
            else:
                self.add_creation_cell()
                gobject.idle_add(widget.get_treeview().scroll_to_point, 0, 0)
        elif not category:
            widget.remove(category_row, True)
        
        self.plugin.config.categories_list = []
        
        for category_row in widget:
            if not category_row is self.creation_row:
                self.plugin.config.categories_list.append(category_row.category)
    
    def on_categories_list__key_press_event(self, widget, event):
        selected_row = widget.get_selected()
        
        if event.keyval == gtk.keysyms.Delete and \
            selected_row is not self.creation_row:
            widget.remove(selected_row, True)
    
    def on_editing_started(self, renderer, editable, path):
        category_row = self.categories_list[path]
        
        if category_row.category == self.creation_hint:
            editable.delete_text(0, -1)

class CategoryColumn(Column):
    def __init__(self, magic_content):
        Column.__init__(self, "category", editable=True, use_markup=True, \
            expand=True)
        
        self.magic_content = magic_content
        self.renderer = None
    
    def on_attach_renderer(self, renderer):
        self.renderer = renderer
    
    def renderer_func(self, renderer, data):
        if data == self.magic_content:
            renderer.set_property("foreground", "gray")
            renderer.set_property("style", pango.STYLE_ITALIC)
        else:
            renderer.set_property("foreground", None)
            renderer.set_property("style", pango.STYLE_NORMAL)
