# 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 logging
log = logging.getLogger("lottanzb.plugins.newzbin")

from kiwi.ui.delegates import ProxyDelegate, Delegate
from kiwi.ui.dialogs import info, error

from lottanzb.util import gproperty, gsignal, _
from lottanzb.plugins import PluginBase, PluginPrefsTabBase
from lottanzb.plugins.newzbin import interface
from lottanzb.modes import standalone

class Plugin(PluginBase):
    title = _("Newzbin")
    description = _("Use the Newzbin.com service to download NZB files.")
    author = _("LottaNZB Development Team")
    
    gsignal("add-dialog-opened", object)
    
    def __init__(self, app, config):
        PluginBase.__init__(self, app, config)
        
        # If the user upgrades from a application version that didn't have the
        # Newzbin plug-in, the user shouldn't have to enable it manually if
        # the Newzbin features has been used before.
        # LottaNZB can do that automatically.
        def on_mode_changed(*args):
            """
            Enables the plug-in if this is the first time the plug-in has been
            loaded and if the user has already specified a Newzbin username
            and password.
            """
            
            mode = self.app.mode_manager.active_mode
            
            if self.config.first_usage and not self.enabled:
                try:
                    assert mode.hella_config.newzbin_support()
                except (AttributeError, AssertionError):
                    pass
                else:
                    self.enabled = True
                    
                    log.info(_("The Newzbin plug-in has been enabled "
                        "automatically."))
        
        if self.app.mode_manager.active_mode:
            on_mode_changed(self.app.mode_manager.active_mode)
        else:
            self.app.mode_manager.connect(
                "notify::active-mode", on_mode_changed
            )
    
    def show_add_dialog(self, *args):
        dialog = AddNewzbinDialog(self)
        dialog.show(self.app.main_window)
        
        self.emit("add-dialog-opened", dialog)
    
    def on_main_window_ready(self, main_window):
        file_menu = main_window.file_menu
        
        add_icon = gtk.Image()
        add_icon.set_from_stock(gtk.STOCK_ADD, gtk.ICON_SIZE_MENU)
        
        menu_item = gtk.ImageMenuItem(_("Add file from Newzbin.com"))
        menu_item.set_image(add_icon)
        menu_item.connect("activate", self.show_add_dialog)
        
        self.insert_menu_item(file_menu, menu_item, main_window.menu_add)
    
    def get_prefs_tab_class(self):
        """
        While the Newzbin plug-in can be used in front-end mode, it's not
        possible to change the credentials. Don't display the Newzbin
        preferences tab in this case.
        """
        
        mode = self.app.mode_manager.active_mode
        
        if isinstance(mode, standalone.Mode):
            return PluginBase.get_prefs_tab_class(self)

class AddNewzbinDialog(Delegate):
    gladefile = "plugin_newzbin_add_dialog"
    
    def __init__(self, plugin):
        Delegate.__init__(self)
        
        self.plugin = plugin
        self.name_lambdas = [lambda name, downloader: "%s.nzb" % name]
    
    def on_id__content_changed(self, widget):
        try:
            int(widget.get_text())
        except ValueError:
            self.add.set_sensitive(False)
        else:
            self.add.set_sensitive(True)
    
    def enqueue(self):
        report_id = self.id.get_text()
        mode_manager = self.plugin.app.mode_manager
        
        if isinstance(mode_manager.active_mode, standalone.Mode):
            hella_config = mode_manager.active_mode.hella_config
            
            if hella_config.newzbin_support():
                downloader = interface.Downloader( \
                    hella_config.newzbin_username, \
                    hella_config.newzbin_password, \
                    report_id)
                
                downloader.connect("completed", self.on_downloader_completed)
                downloader.start()
        else:
            self.plugin.app.backend.newzbinEnqueue(report_id)
    
    def on_downloader_completed(self, downloader):
        if downloader.exception:
            error(downloader.exception)
        else:
            name = downloader.name
            
            for name_lambda in self.name_lambdas:
                name = name_lambda(name, downloader)
            
            self.plugin.app.backend.enqueue(downloader.filename, name)
    
    def on_plugin_newzbin_add_dialog__response(self, dialog, response):
        if response == gtk.RESPONSE_OK:
            self.enqueue()
        
        dialog.destroy()

class PrefsTab(PluginPrefsTabBase):
    gladefile = "plugin_newzbin_prefs"
    hella_fields = ["newzbin_username", "newzbin_password"]
