# -*- coding: utf-8 -*-

#   This file is part of emesene.
#
#    Emesene 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.
#
#    emesene 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 emesene; if not, write to the Free Software
#    Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA

import os
import Plugin
import gtk
import dialog
import stock
import desktop
#from ImageFileChooser import ImageFileChooserDialog
#from ImageAreaSelector import ImageAreaSelectorDialog
from Theme import resizePixbuf


class BackDialog(gtk.Window):
    '''a dialog to set the background image'''
    #def __init__(self, parent, config, filename, resize):
    def __init__(self, response, filename, resize):
        #gtk.Dialog.__init__(self , _('Background config'), parent , \
        #        gtk.DIALOG_MODAL | gtk.DIALOG_DESTROY_WITH_PARENT , \
        #        (gtk.STOCK_CANCEL, gtk.RESPONSE_REJECT, \
        #        gtk.STOCK_OK, gtk.RESPONSE_ACCEPT))

	gtk.Window.__init__(self)
        self.set_title(_('Background Config'))
        self.set_border_width(4)
        self.set_position(gtk.WIN_POS_CENTER)	
	
	#self.config = config
        self.filename = filename
	self.resize = resize

        #self.set_default_response(gtk.RESPONSE_ACCEPT)
	self.response_ok = response
	self.hbox = gtk.HBox()
	self.imagebox = gtk.HBox()

	self.image = gtk.Image()

        try:
            pixbuf =  gtk.gdk.pixbuf_new_from_file(self.filename)
	    pixbuf = resizePixbuf(pixbuf, 128,128)
            self.image.set_from_pixbuf(pixbuf)
	except:
            self.filename = None

        self.button = gtk.Button(_('Image'))
	self.button.connect('clicked', self.clickPixmap)

        self.imagebox.pack_start(self.image)
        self.hbox.pack_start(self.button)

	self.vbox = gtk.VBox(spacing=4)
	self.vbox.pack_start(self.imagebox)	
	self.vbox.pack_start(self.hbox)
			
	self.check = gtk.CheckButton(_('Resize image'))
	#if self.resize:
	self.check.set_active(resize)

	self.vbox.pack_start(self.check)

	b_accept = gtk.Button(stock=gtk.STOCK_OK)
        b_cancel = gtk.Button(stock=gtk.STOCK_CANCEL)

        b_accept.connect('clicked', self._on_response_ok)
        b_cancel.connect('clicked', self._on_response_cancel)

	hbbox = gtk.HButtonBox()
        hbbox.set_spacing(4)
        hbbox.set_layout(gtk.BUTTONBOX_END)

        hbbox.pack_start(b_cancel, False)
        hbbox.pack_start(b_accept, False)

	#self.vbox.pack_start(self.hbox)
	#self.vbox.pack_start(self.check)
	#self.vbox.show_all()
	self.vbox.pack_start(hbbox)

        self.add(self.vbox)

        self.show_all()


    def clickPixmap(self, arg):
        #self.filename = ImageAreaSelectorDialog(self.config).run()[1]
	def _on_image_selected(response, path):
            self.filename = path
        try:
            pixbuf = gtk.gdk.pixbuf_new_from_file(self.filename)
            pixbuf = resizePixbuf(pixbuf, 128,128)
            self.image.set_from_pixbuf(pixbuf)
            self.image.show()
        except:
            self.filename = None
            self.image.hide() 
	
	dialog.ImageChooser(os.path.expanduser('~'), _on_image_selected).show()

    #def run(self):
        #option = gtk.Dialog.run(self)
        #self.resize = self.check.get_active()
        #self.destroy()   
        #return (self.filename, self.resize)

    def _on_response_ok(self, button):
         self.destroy()
         self.response_ok(self.filename,
                 int(self.check.get_active()))
                 
    def _on_response_cancel(self, button):
         self.destroy()


class MainClass( Plugin.Plugin ):
    '''Main plugin class'''
    
    def __init__( self, controller, msn ):
        '''Contructor'''

        Plugin.Plugin.__init__( self, controller, msn )

        self.description = _('Changes conversation background.')
        self.authors = { 'Andre Ramaciotti da Silva' : 'andre.ramaciotti@gmail.com' }
        self.displayName = _('Background')
        self.name = 'Background'
        
        self.controller = controller
        self.config = controller.config
	self.config.readPluginConfig(self.name)
	self.filename = self.config.getPluginValue(self.name, 'filename', \
			None)
	#self.resize = self.config.getPluginValue(self.name, 'resize', \
	#		False)
	self.resize = int(self.config.getPluginValue(self.name, 'resize', '1'))
        self.handlerId = None
        self.enabled = False

    def start( self ):
        '''start the plugin'''
	self.convmanagerId = self.controller.conversationManager.connect( \
            'new-conversation-ui', self.openWindow)
	try:
	    self.bg = gtk.gdk.pixbuf_new_from_file(self.filename)
	except:
	    self.bg = None
	
        self.enabled = True

    def openWindow(self, conversationManager, conversation, window):
        '''A new window (or tab) has been created...'''
	if self.bg:
	    if self.resize:
	        h, w = conversation.ui.textview.window.get_size()
		#self.bg = resizePixbuf(self.bg , h,w)
		scaled = self.bg.scale_simple(h, w, gtk.gdk.INTERP_BILINEAR)
		pixmap = scaled.render_pixmap_and_mask()[0]
	    else:
	        pixmap = self.bg.render_pixmap_and_mask()[0]

	    style = conversation.ui.textview.get_style()
	    textwnd = conversation.ui.textview.get_window(gtk.TEXT_WINDOW_TEXT)

	    textwnd.set_back_pixmap(pixmap, False)

    def stop( self ):    
        '''stop the plugin'''
	self.controller.conversationManager.disconnect(self.convmanagerId)
        self.enabled = False

    def check(self):
        return (True, 'Ok')

    def configure(self):
	#self.filename, self.resize = BackDialog(None, self.config, \
	#		self.filename, self.resize).run()

	def _on_configure_ok(filename, resize):	

	    self.filename = filename
	    self.resize = resize

	    self.config.setPluginValue(self.name, 'filename', filename)
	    self.config.setPluginValue(self.name, 'resize', resize)
	    try:
            	self.bg = gtk.gdk.pixbuf_new_from_file(self.filename)
	    except:
            	self.bg = None
	
	BackDialog(_on_configure_ok, self.filename, self.resize).show()
        return True

