# 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 logging
import gtk

from time import strftime, localtime

from kiwi.ui.delegates import Delegate
from kiwi.ui.widgets.combo import ProxyComboBox

from lottanzb.log import RecordSource
from lottanzb.core import App
from lottanzb.util import _

class Window(Delegate):
    gladefile = "log_window"
    
    def __init__(self):
        Delegate.__init__(self)
        
        # Only show debug messages by default if LottaNZB is actually executed
        # using the --debug argument.
        if App().debug:
            default_level = logging.DEBUG
        else:
            default_level = logging.INFO
        
        color = gtk.widget_get_default_colormap().alloc_color
        
        self.log = App().log
        self.textbuffer = self.content._textbuffer
        self.textbuffer.create_tag("error", foreground_gdk=color("red"))
        self.textbuffer.create_tag("debug", foreground_gdk=color("grey"))
        
        self.v_adjustment = self.scrolled_window.get_vadjustment()
        self.end_mark = self.textbuffer.create_mark("end", \
            self.textbuffer.get_end_iter(), False)
        
        self.setup_filter("level", [
            (_("Debug"), logging.DEBUG),
            (_("Info"), logging.INFO),
            (_("Warning"), logging.WARNING),
            (_("Error"), logging.ERROR)
        ], default_level)
        
        self.setup_filter("source", [
            (_("LottaNZB and HellaNZB"), RecordSource.BOTH),
            (_("LottaNZB only"), RecordSource.LOTTA),
            (_("HellaNZB only"), RecordSource.HELLA)
        ])
        
        self.update()
        self.log.connect("record-added", self.handle_log_record_added)
    
    def setup_filter(self, name, entries, preselect=None):        
        widget = ProxyComboBox()
        widget.prefill(entries)
        
        if entries:
            if preselect is None:
                preselect = entries[0][1]
            
            widget.update(preselect)
        
        widget.connect("changed", self.update)
        widget.show()
        
        self.get_widget("%s_container" % name).add(widget)
        
        setattr(self, name, widget)
    
    def get_records(self):
        level = self.level.read()
        source = self.source.read()
        store = self.log.filter_by_source(source).filter_by_level(level)
        
        return store.records
    
    def handle_log_record_added(self, log, record):
        self.display_record(record)
    
    def display_record(self, record):
        if self.source.read() == RecordSource.BOTH:
            if record.source == RecordSource.LOTTA:
                source = "LottaNZB\t"
            else:
                source = "HellaNZB\t"
        elif record.source == self.source.read():
            source = ""
        else:
            return
        
        if record.levelno < self.level.read():
            return
        
        line = strftime("%H:%M:%S", localtime(record.created)) + "\t" + \
            source + record.getMessage() + "\n"
        
        if record.levelno >= logging.WARNING:
            tag = "error"
        elif record.levelno == logging.DEBUG:
            tag = "debug"
        else:
            tag = ""
        
        end_iter = self.textbuffer.get_end_iter()
        adjust = self.v_adjustment
        
        if tag:
            self.textbuffer.insert_with_tags_by_name(end_iter, line, tag)
        else:
            self.textbuffer.insert(end_iter, line)
        
        # Auto-scroll the log message TextView if the user has manually moved
        # the scrollbar to the bottom.
        if adjust and adjust.value and \
            adjust.value + adjust.page_size == adjust.upper:
            self.content.scroll_to_mark(self.end_mark, 0.05, True, 0.0, 1.0)
    
    def update(self, *args):
        self.content.update("")
        self.v_adjustment.set_value(0)
        
        for record in self.log.records:
            self.display_record(record)
    
    def on_save__clicked(self, widget):
        def handleResponse(dialog, response):
            if response == gtk.RESPONSE_OK:
                filename = dialog.get_filename()
                
                try:
                    logfile = open(filename, "w")
                except IOError, e:
                    logging.error(_("Could not open %s to write message log: %s") % (filename, e.strerror))
                    return
                
                try:
                    logfile.write(self.content.read())
                    logfile.close()
                except IOError, e:
                    logging.error(_("Could not write message log to %s: %s") % (filename, e.strerror))
                else:
                    logging.info(_("Message log saved to %s.") % (filename))
            
            dialog.destroy()
        
        dialog = gtk.FileChooserDialog(_("Save message log"),
            self.toplevel, gtk.FILE_CHOOSER_ACTION_SAVE,
            (gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL, gtk.STOCK_SAVE, gtk.RESPONSE_OK))
        
        dialog.connect("response", handleResponse)
        dialog.set_default_response(gtk.RESPONSE_OK)
        
        dialog.show()
    
    def on_clear__clicked(self, widget):
        self.content.update("")
