#  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 PMail; 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
import string
try:
  import gnome
except:
  pass
import os
import string
import types

import Base
import config
import GladeWindow
import mail
from mail.NewMessage import NewMessage
import gutil

def show(parent, to=None):
  w = Compose(parent)
  if to:
    w._to.insert_defaults(to)    
  w.show()

def forward(parent, message, type=mail.INLINE):
  w = Compose(parent)
  w.forward(message, type)
  w.show()

def reply(parent, message, type = mail.QUOTED, reply_to_all=0):
  w = Compose(parent)
  w.reply(message, type, reply_to_all)
  w.show()

def restore(parent, message):
  w = Compose(parent)
  w.restore(message)
  w.show()

class Compose(GladeWindow.Window):
  def __init__(self, parent):
    GladeWindow.Window.__init__(self)

    sigs = { 'send': self.send,
             'close': self.close,
             'delete_event': self.delete_event,
             'save': self.save,
             'attach': self.attach,
             'select_icon': self.select_attachment,
             'delete_attachment': self.delete_attachment,
             'spelling': self.spell
             }
    self._glade.signal_autoconnect(sigs)

    self._attachments = []
    self._selected_attachment = None
    self._was_sent = 0
    self._is_reply = 0
    self._attach_related_message = 0

    self._body.set_word_wrap(1)
    self._iconlist.connect('drag_data_received', self.drag_data_received)
    self._body.connect('drag_data_received', self.drag_data_received)    
    #self._att_list.connect('drag_motion', self.drag_motion)
    #self._att_list.connect('drag_leave', self.drag_leave)
    self._body.drag_dest_set(DEST_DEFAULT_ALL,
                             [('text/uri-list', 0, -1)],
                             GDK.ACTION_COPY)
    self._iconlist.drag_dest_set(DEST_DEFAULT_ALL,
                             [('text/uri-list', 0, -1)],
                             GDK.ACTION_COPY)
    

  def set_subject(self, message, prepend):
    self._subject.set_text(mail.get_subject(message, prepend))

  def insert_message_text(self, message, type=None):
    if type == mail.ATTACHMENT:
      #we'll do this later
      self._attach_related_message = 1
    
    self._body.insert_defaults(mail.get_message_text(message, type))
    

  def forward(self, message, type):
    self._message = message

    self.set_subject(message, 'Fwd:')
    self.insert_message_text(message, type)
    self._related_message = message

  def reply(self, message, type, reply_to_all):
    self._is_reply = 1
    self._message = message

    self.set_subject(message, 'Re:')

    to = message.get_header('Reply-to')
    if not to:
      to = message.get_header('From')    
    self._to.insert_defaults(to)
    self.insert_message_text(message, type)
    self._related_message = message

  def restore(self, message):
    s = message.get_header('subject')
    if s: self._subject.set_text(s)
    s = message.get_header('to')
    if s: self._to.insert_defaults(s)
    s = message.get_header('cc')
    if s: self._the_cc.insert_defaults(s)

    self.insert_message_text(message)
                                
  def name(self):
    return 'Compose'

  def save(self, d):
    #FIXME
    box = gutil.select_folder_box('Save Folder:',
                                  mail.get_mailbox_config_value('drafts_box'),
                                  'Select a folder to save to',
                                  self)
    if box:
      m = self.create_message()
      m.set_draft()
      m.append(box)
      self._was_sent = 1
      self.close()
    

  def __check_close(self):
    if not self._was_sent:
      if not gutil.question_box('Compose', 'You have not sent this message, would you like to close anyway?\n(Use "Save" to save to your drafts)', self._window):
        return 0
    return 1

  def delete_event(self, d=None, e=None):
    return not self.__check_close()

  def close(self, d=None):
    if self.__check_close():
      self._window.destroy()
      del self

  def destroy(self, d):
    #FIXME: how to keep from destroying?
    pass

  def drag_data_received(self, widget, context, x, y, data, info, time):
    #print 'drag_data_received:', widget, context, x, y, data.data, info, time
    files = string.split(data.data[:-1], '\r\n')
    for file in files:
      if len(file):
        self._add_attachment(file)

  def delete_attachment(self, n):
    if self._selected_attachment != None and len(self._attachments):
      data = self._iconlist.get_icon_data(self._selected_attachment)
      self._iconlist.remove(self._selected_attachment)
      self._attachments.remove(data)

  def select_attachment(self, list, pos, event):
    self._selected_attachment = pos

  def attach(self, d):
    #FIXME: use gnome version
    #filename =  GtkExtra.file_sel_box('Select Attachment', TRUE)
    filename = gutil.file_selection_box(parent=self._window)
    if filename:
      self._add_attachment(filename)

  def _add_attachment(self, filename):
    data = filename    
    self._attachments.append(data)

    type = gnome.mime.type_of_file(filename)
    iconfile = gutil.iconfile_for_mimetype(type)

    idx = self._iconlist.append(iconfile,
                                os.path.split(filename)[1])
    self._iconlist.set_icon_data(idx, data)
    #self._iconlist.append(gnome.ui.STOCK_PIXMAP_ATTACH, os.path.split(filename)[1])

  def _process_addresses(self, text):
    addrs = []
    split = string.split(text, '\n')
    for line in split:
      if len(line):
        s = string.split(line, ',')
        addrs = addrs + s

    for i in range(len(addrs)):
      email = mail.address_part(addrs[i])
      has_at = string.find(email, '@')
      if has_at == -1:
        addrs[i] = email + '@' + mail.get_config('default_domain')

    #res = string.join(addrs, ',')
    return addrs

  def create_message(self):
    to = self._process_addresses(self._to.get_chars(0, -1))
    cc = self._process_addresses(self._the_cc.get_chars(0, -1))
    bcc = self._process_addresses( self._bcc.get_chars(0, -1))
    
    m = NewMessage(to, cc, bcc, self._subject.get_text())
    m.start_message(len(self._attachments) or self._attach_related_message)
    m.set_body(self._body.get_chars(0, -1))

    if self._attach_related_message:
      m.add_messsage_attachment(self._related_message)

    for file in self._attachments:
      m.add_attachment(file)

    return m
    
  def send(self, d):
    m = self.create_message()
    res = m.send()
    if not len(res):
      box = mail.get_mailbox_config_value('sent_box')
      if box:
        m.append(box)

      if self._is_reply:
        self._related_message.set_answered()
        
      self._was_sent = 1
      self.close()
    
  def spell(self, d=None):
    #Spell.show(self, self._body.get_chars(0, -1))
    pass
    
