# 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 re

import logging
log = logging.getLogger(__name__)

from os.path import isfile, basename

from kiwi.ui.delegates import Delegate

from lottanzb.core import App
from lottanzb.util import gproperty, _
from lottanzb.config import ConfigSection

class Config(ConfigSection):
    last_location = gproperty(type=str)

class Dialog(Delegate):
    gladefile = "add_file_dialog"
    
    def __init__(self, a_file=None):
        Delegate.__init__(self)
        
        # Since we already have a parameter, it wouldn't be such a good idea
        # to pass the configuration from the main window to the dialog using
        # the constructor.
        self.config = App().config.gui.add_file
        
        self.toplevel.get_filter().add_pattern("*.nzb")
        self.toplevel.get_filter().add_pattern("*.NZB")
        
        self.name_lambdas = [lambda name: "%s.nzb" % name]
        
        if a_file:
            try:
                self.toplevel.select_filename(a_file)
            except:
                log.error(_("Could not set the filename."))
        elif self.config.last_location:
            # A file passed as a parameter to this class always has priority
            # when it comes to deciding what location to display.
            self.toplevel.set_current_folder(self.config.last_location)
    
    def enqueue_selection(self):
        files = self.toplevel.get_filenames()
        
        for a_file in files:
            if len(files) == 1:
                name = self.name.get_text()
            else:
                name = self.pretty_nzb_name(a_file)
            
            if isfile(a_file):
                # Build the new name of the download.
                for name_lambda in self.name_lambdas:
                    name = name_lambda(name)
                
                # Enqueueing an NZB file over the network may take one or two
                # seconds. That's why the dialog is hidden before this is done.
                self.toplevel.hide()
                
                App().backend.enqueue(a_file, name)
            else:
                self.toplevel.set_current_folder(self.toplevel.get_filename())
    
    def add_option(self, label, widget):
        widget.show()
        
        label = gtk.Label(label)
        label.show()
        
        rows = self.table.get_property("n-rows")
        columns = self.table.get_property("n-columns")
        
        self.table.resize(rows + 1, columns)
        self.table.attach(label, 0, 1, rows, rows + 1, gtk.SHRINK, gtk.SHRINK)
        self.table.attach(widget, 1, 2, rows, rows + 1)
    
    def on_add_file_dialog__response(self, widget, response):
        if response == gtk.RESPONSE_OK:
            self.enqueue_selection()
        
        # Save the current location for future usage.
        self.config.last_location = self.toplevel.get_current_folder()
        
        widget.destroy()
    
    def on_add_file_dialog__selection_changed(self, widget):
        files = widget.get_filenames()
        
        if len(files) > 1:
            self.name.set_text(_("Multiple files selected"))
            self.name.set_sensitive(False)
        else:
            if len(files) == 1 and isfile(files[0]):
                self.name.set_text(self.pretty_nzb_name(files[0]))
            else:
                self.name.set_text("")
            
            self.name.set_sensitive(True)
    
    def check_focus(self):
        """
        Workaround for a really strange PyGTK bug that cannot be reproduced all
        the time and not by everyone. It has been reported here:
        https://bugzilla.gnome.org/show_bug.cgi?id=555384
        """
        
        pass
    
    @staticmethod
    def pretty_nzb_name(name):
        name = basename(name)
        name = re.compile(r"\.nzb", re.I).sub("", name)
        name = re.compile(r"[\._]").sub(" ", name)
        
        return name
