#  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:
  from gnome.xmhtml import *
except:
  pass
import urllib
import tempfile
import os
import string
import urlparse

import Base
import config
import mail
from PmailGtkXmHTML import *
import MsgWindow
import Compose
import gutil

class Window(MsgWindow.Window):
  def __init__(self, mainWindow):
    MsgWindow.Window.__init__(self, mainWindow)

    #self._debug = 1
    self._tracking = 0
    self._temp_files = []
    self._displayed_message = None
    self._opener = urllib.URLopener()      
    self._part_data = None
    
    self._html = PmailGtkXmHTML()
    self._html.set_anchor_buttons(FALSE)
    self._html.set_anchor_underline_type(1)
    self._html.set_image_proc(self.get_image_file_name)
    self._html.show()

    label = GtkLabel('Body')
    self.append_page(self._html, label)

    #self._html.connect("link", self.link)
    #self._html.connect("html_event", self.event)
    self._html.connect("activate", self.activate_link)
    self._html.connect("anchor_track", self.track_anchor)

  def get_image_file_name(self, url):
    if url[:4] == 'cid:':
      part = self._displayed_message.get_parts();
      pid = '<%s>' % url[4:]
      part = part.find_part_with_id(pid)
      if part:
        newfile = self._displayed_message.make_temp_file(part)
        return newfile
    elif url[:5] == 'http:':
      h = self._opener.open(url)
      headers = h.info()
      mime = headers.getheader('Content-type')
      filename = tempfile.mktemp()
      self._temp_files.append(filename)
      f = open(filename, "w")      
      f.write(h.read())
      f.close()
      h.close()
      self.debug('saved image to: %s' % filename)
      return filename
      
    return url

  def remove_temp_files(self):
    if self._displayed_message:
      self._displayed_message.clean_up_temp_files()
    for file in self._temp_files:
      os.remove(file)
    self._temp_files = []

  def name(self):
    return 'GtkMessageWindow'

  def link(self, html, info):
    self.debug('link: %s' % info)

  def event(self, html, info):
    self.debug('event: %s' % info)

  def activate_link(self, html, info):
    self.debug('activate_link: %s' % info.href)
    url = urlparse.urlparse(info.href)
    
    if url[0] == 'attachment':
      part = self._part_data[string.replace(url[2], '/', '.')]
      fileName = part.parameters().get('name')
      if not fileName:
        fileName = 'attachment'

      fileName = gutil.file_save_box(fileName, title='Save As')
      
      if fileName:
        self.debug('save as: %s' % fileName)
        part.write_to_file(fileName, 0)
    elif url[0] == 'mailto':
      Compose.show(self, url[2])
      pass
    else:
      gutil.exec_browser(info.href)
      #FIXME: use to external viewer (use mailcap??)
      #use the attachment view stuff
      pass
    
  def track_anchor(self, html, info):
    self.debug('track: %s' % info.href)
    if self._tracking:
      self._mainWindow.pop_status(self.name())
    if info.href:
      self._tracking = 1
      self._mainWindow.show_status(self.name(), info.href)
    else:
      self._tracking = 0

  def set_text(self, text):
    self._html.freeze()

    fname = config.getParam(None, 'Display', 'messageFont')
    if self._font_name != fname:
      self._font_name = fname
      self._font = load_font(fname)
      
    if self._font:
      print "setting font to: ", fname
      self._html.set_font_family(fname, "*")
    
    self._html.source(text)
    self._html.thaw()

  def display_message(self, message):
    self._part_data =  message.get_parts().partsDictionary()
    self.remove_temp_files()
    self._temp_files = []
    self._displayed_message = message
    txt, self._attachments = message.get_text(1)    
    html = '<HTML><BODY>' + txt + '</BODY></HTML>\n'
    self.debug(html)
    self.set_text(html)
    self.update_notebook()
    

    
    
