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

true = 1
false = 0

class PMailObject:
  def __init__(self, debug = 0, log = 0):
    self._debug = debug
    self._log = log
    self._config_params = []

  def log_error(self, message):
    print '%s.%s: ERROR: ' % (self.__class__.__module__, self.__class__.__name__), message    

  def log(self, message):
    if self._log:
      print '%s.%s:' % (self.__class__.__module__, self.__class__.__name__), message          

  def debug(self, message):
    if self._debug:
      print '%s.%s:' % (self.__class__.__module__, self.__class__.__name__), message

  def __setitem__(self, key, v):
    exec 'old = self._%s' % key #raise if it's not valid
    self.__dict__['_%s' % key] = v
    self.hook_setitem(key, v)

  def hook_setitem(self, key, v):
    pass

  def __getitem__(self, key):
    try:
      exec 'res = self.%s()' % key
    except AttributeError:
      res = self.__dict__['_%s' % key]
    return res

  def get_config(self):
    dict = {}
    dict['class'] = self.__class__.__name__
    for name in self._config_params:
      exec "dict['%s'] = self._%s" % (name, name)
    return dict

  def read_config(self, dict):
    for kv in dict.items():
      key, val = kv
      if key != 'class':
        try:
          self[key] = val
        except AttributeError:
          self.log_error("invalid key: '%s' found in config, ignoring" % key)

  def add_config_params(self, params):
    self._config_params = self._config_params + params

def foreach(func, seq, *args):
  for item in seq:
    apply(func, (item,) + args)

def subtract_lists(list1, list2):
  foreach(lambda x, l=list1: x in l and l.remove(x), list2)

def add_lists(list1, list2):
  foreach(lambda x, l=list1: x not in l and l.append(x), list2)

def filter_map(func, list, *args):
  res = []
  for item in list:
    r = apply(func, (item,) + args)
    if r: res.append(r)
  return res

