#  PMail - GNOME/GTK/Python email client
#  Copyright (C) 2000 Scott Bender <sbender@harmony-ds.com>

#  This file is part of PMail.

#  PMail 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, or (at your option)
#  any later version.

#  PMail 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 GNU Emacs; see the file COPYING.  If not, write to
#  the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
#  Boston, MA 02111-1307, USA.  

from gtk import *
import GtkExtra
try:
  import gnome.ui
except:
  pass
import string
from StringIO import StringIO

import Base
import gutil
import config
try:
  import _pmailextensions
except:
  pass
import mail.Message
import mail.Plugin
import MsgWindow


class Window(GtkNotebook, Base.PMailObject):
  def __init__(self, mainWindow):
    GtkNotebook.__init__(self)
    Base.PMailObject.__init__(self, debug=0)

    self.set_tab_pos(POS_TOP)
    self.set_scrollable(1)

    self._mainWindow = mainWindow
    self._font_name = None
    self._font = None
    self._attachments = None

  def redisplay(self):
    if self._displayed_message:
      self.display_message(self._displayed_message)

  def select_attachment(self, list, pos, event):
    if event.button == 3:

      num, part = self._iconlist.get_icon_data(pos)
      type = part.mime_type()

      mf = GtkExtra.MenuFactory(GtkExtra.MENU_FACTORY_MENU)
      mf.add_entries([
        ('Open', None, self.do_command, part, 'open')])

      mime_entries = []
      keys = gnome.mime.get_keys(type)
      for key in keys:
        if key[:5] == 'open.':
          idx = string.rindex(key, '.')
          name = key[idx+1:]

          entry = (name, None, self.do_command, part, key)
          mime_entries.append(entry)
      if len(mime_entries):
        mime_entries.insert(0, ('<separator>', None, None))
        mf.add_entries(mime_entries)

      mf.add_entries([
        ('<separator>', None, None),
        ('Save As...', None, self.do_save_as, part),
        ])

      view = _pmailextensions.gnome_mime_get_value(type, 'view')
      if view:
        mf.add_entries([('View', None, self.do_command, part, 'view')])

      edit = _pmailextensions.gnome_mime_get_value(type, 'edit')
      if edit:
        mf.add_entries([('Edit', None, self.do_command, part, 'edit')])
      
      menu = mf.get_menu('')
      menu.popup(None, None, None, event.button, event.time)

  def do_save_as(self, d, part):
    fname = gutil.file_selection_box(part.parameters().get('name'),
                                     title='Save As')
    if fname:
      part.write_to_file(fname, remove_when_done=0)

  def do_command(self, d, part, key):
    fileName = part.write_to_file()
    gutil.exec_mime_open(part.mime_type(), key, fileName)
      
  def update_notebook(self):
    nc = len(self.children())
    if nc > 1:
      for i in range(1, nc):
        self.remove_page(1)
    if self._attachments and len(self._attachments):
      sw = GtkScrolledWindow()
      self._iconlist = gnome.ui.GnomeIconList()
      self._iconlist.connect('select_icon', self.select_attachment)
      sw.add(self._iconlist)
      self._iconlist.show()
      label = GtkLabel('Attachments')
      self.append_page(sw, label)
      sw.show()

      for num, part in self._attachments.items():
        fileName = part.parameters().get('name')
        parttype = part.mime_type()

        if not fileName:
          fileName = parttype
          iconname = parttype
        else:
          iconname = '%s (%s)' % (fileName, parttype)

        pixmap_file = gutil.iconfile_for_mimetype(parttype)
        idx = self._iconlist.append(pixmap_file, iconname)
        self._iconlist.set_icon_data(idx, (num, part))
        
        
        if part.type() == 'image':
          sw = GtkScrolledWindow()
          image_file = part.write_to_file()
          pixmap = gnome.ui.GnomePixmap(image_file)
          sw.add_with_viewport(pixmap)
          pixmap.show()
          label = GtkLabel(fileName)
          self.append_page(sw, label)
          sw.show()
        elif part.type() == 'message' and part.subtype() == 'rfc822':
          w = MsgWindow.create_message_window(self._mainWindow)
          msg = mail.Message.TextMessage(StringIO(part.data()))
          sub = msg.get_header('subject')          
          label = GtkLabel(sub or 'Message Attachment')
          w.show()
          self.append_page(w, label)
          w.display_message(msg)
          mail.Plugin.call_plugins('message_displayed', (msg, w))
    
          

##           fname = config.getParam(None, 'Display', 'messageFont')
##           if self._font_name != fname:
##             self._font_name = fname
##             self._font = load_font(fname)

##           if self._font:
##             text.insert(self._font, None, None, part.data())
##           else:
##             text.insert_defaults(part.data())
          

import TextMsgWindow
import XmHTMLMsgWindow
import MozillaMsgWindow

def create_message_window(mainWindow):
  mw = config.getParam(None, 'Display', 'messageDisplayClass',
                       'TextMsgWindow')

  if mw == 'MozillaMsgWindow' and MozillaMsgWindow.have_mozilla:
    res = MozillaMsgWindow.Window(mainWindow)
  elif mw == 'XmHTMLMsgWindow':
    res = XmHTMLMsgWindow.Window(mainWindow)
  elif mw == 'TextMsgWindow' or not mw or not len(mw):
    res = TextMsgWindow.Window(mainWindow)

  return res


