#  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.  


import time
import string
import rfc822
import os
import array
from htmlentitydefs import entitydefs

import config

htmlc = None

if not htmlc:
  htmlc = {}
  htmlc['\r'] = '<br>'
  for key, val in entitydefs.items():
    htmlc[val] = '&' + key


normalDisplayHeaders = ['subject', 'date', 'from', 'to', 'cc', 'origanization', 'reply-to']
briefDisplayHeaders = ['from', 'subject']


NORMAL_HEADERS = 1
ALL_HEADERS = 2
BRIEF_HEADERS = 3

INLINE = 0
QUOTED = 1
ATTACHMENT = 2

def get_user_name():
  for name in ('LOGNAME', 'USER', 'LNAME', 'USERNAME'):
    user = os.environ.get(name)
    if user:
      return user

  try:
    import pwd
    return pwd.getpwuid(os.getuid())[0]
  except:
    return None

def get_user_full_name():
  try:
    import pwd
    return pwd.getpwuid(os.getuid())[4]
  except:
    return ''

def get_host_name():
  try:
    import socket
    return socket.gethostbyaddr(socket.gethostname())
  except:
    return None
 
def setup_default_config():
  set_config('headerView', NORMAL_HEADERS)
  #set_config('displayHeaders', normalDisplayHeaders)
  set_config('quote_string', '>  ')
  set_config('reply_type', QUOTED)
  set_config('forward_type', INLINE)
  set_config('users_name', get_user_full_name())
  set_config('reply_to', '')
  set_config('sig', '')
  set_config('bcc', '')
  set_config('smtp_server', 'localhost')
  set_config('smtp_user', '')
  set_config('empty_trash', 0)
  set_config('wrap_column', 72)

  email = get_user_name()
  hostName = get_host_name()

  if hostName:
    hostName = hostName[0]
    email = '%s@%s' % (email, hostName)
  else:
    hostName = ''

  set_config('email_address', email)
  set_config('default_domain', hostName)
  

def get_config(name, default=None):
  return config.getParam(None, 'Mail', name, default)

def set_config(name, val):
  config.setParam(None, 'Mail', name, val )

def mailbox_config_value(box):  
  d = box != 'None' and { 'source_id': box.source()['unique_id'], 'path': box.path() }  or None
  return d

def set_mailbox_config_value(name, box):
  set_config(name, mailbox_config_value(box))

def mailbox_from_config(d):
  if d:
    source = source_with_unique_id(d['source_id'])
    if source: return source.mailbox_with_path(d['path'])
  return None

def get_mailbox_config_value(name):
  d = get_config(name)
  return mailbox_from_config(d)

def debug(msg):
  pass

def plainTextToHtml(text):
  res = ''
  for c in text:
    res = res + htmlc.get(c, c)
  return res

def address_part(email):
  name, addr = rfc822.parseaddr(email)
  return addr

def prettyDate(msg, date):
  if date:
    try:
      date = time.strftime('%m/%d/%Y %H:%M:%S', date)
    except ValueError, x:
      date = ''
  else:
    date = ''
  return date

def name_part(text):
  name, addr = rfc822.parseaddr(text)
  if name:
    return name
  return addr
 
def mailtoHeaderHtml(text):
  going = 1
  res = ''
  while len(text):
    try:
      idx = string.index(text, ',')
    except ValueError:
      idx = len(text)
    if len(text):
      addr = text[:idx]
      text = text[idx+1:]
      res = res + '<a href=\"mailto:%s\">%s</a>' \
            % (address_part(addr), plainTextToHtml(addr))
      if len(text):
        res = res + ','
  return res
  

sources = []

def get_sources():
  #global __sources
  return sources

def add_source(source):
  global sources
  if sources == None:
    sources = []
  sources.append(source)

def remove_source(source):
  global sources
  sources.remove(source)

def source_with_unique_id(id):
  r = filter(lambda source, x=id: source['unique_id'] == x, sources)
  if len(r):
    return r[0]
  else:
    return None

def remove_nulls(str):
  s = array.array('c', str)
  for i in range(len(s)):
    if s[i] == '\0':
      s[i] = '0'
  return s.tostring()


def get_subject(message, prepend):
  val = message.get_header('subject')

  lwr = string.lower(val[:len(prepend)])

  if lwr != string.lower(prepend):
    val = prepend + ' ' + val

  return val

def get_message_text(message, type=None):
  txt = ''
  if type == INLINE:
    txt,att = message.get_text(0)
  elif type == QUOTED:
    txt,att = message.get_text(0)
    txt = string.split(txt, '\n')
    newt = ''
    for line in txt:
      newt = newt + get_config('quote_string') + line + '\n'
    txt = newt
  elif not type:
    txt,att = message.get_text(0, 0)

  if type:
    from_ = message.get_header('from')
    if from_ and type != ATTACHMENT:
      txt = '"%s" wrote:\n\n' % name_part(from_) + txt

  return txt
