#  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 pickle
import string
import os
import threading

from Base import *
import Message

class Mailbox(PMailObject):
  def __init__(self, source, parent = None):
    PMailObject.__init__(self, 0)
    self._mailboxes = {}
    self._messages = None
    self._source = source
    self._parent = parent
    self._unseen_count = None
    self._message_count = None
    self._expanded = 0

    self.add_config_params(['message_count', 'unseen_count', 'expanded' ])

  def init_done(self):
    conf = self._source._mailbox_configs.get(self.config_name())
    if conf:
      self.read_config(conf)

  #subclasses can override the locking if the source does not need to be locked
  def can_lock(self):
    return self._source.can_lock()

  def lock(self):
    self._source.lock()

  def unlock(self):
    self._source.unlock()

  def is_selectable(self):
    return 1

  def config_name(self):
    return self.path()

  def source(self):
    return self._source

  def search(self, criteria):
    return self._source.search(self, criteria)
  
  def message_count(self):
    #if self._messages == None:
    if not self._message_count:
      self._message_count = self._source.message_count(self)
    #else:
    #  self._message_count = len(self._messages)
    return self._message_count

  def unseen_count(self):
    #cnt = 0
    #if self._messages != None:
    #  for msg in self._messages:
    #    if not msg.seen():
    #      cnt = cnt + 1
    #  self._unseen_count = cnt
    #else:
    if self._unseen_count == None:
      self._unseen_count = self._source.unseen_count(self)
    return self._unseen_count

  def messages(self, is_selection=0):
    self.lock()
    checked = 0
    try:
      if self._messages == None:
        res = self.load_message_cache(self._source.cache_dir())
        if not res and self._source['check_when_selected']:
          self._messages = self._source._get_messages(self)
          checked = 1
        #if self._messages is None:
        #  self._messages = []
      if is_selection \
         and self._source['check_when_selected'] \
         and not checked \
         or not self._messages:
        self.check_mail()
    finally:
      self.unlock()
    return self._messages

  def messages_loaded(self):
    return self._messages != None

  def check_mail(self, changes=None):
    self._message_count = None
    self._unseen_count = None

  def path(self):
    return self._path

  def name(self):
    return self._name

  def mailboxes(self):
    return self._mailboxes.values()

  def mailbox_with_path(self, path):
    if self._path == path:
      return self
    if self.mailboxes():
      for box in self.mailboxes():
        b = box.mailbox_with_path(path)
        if b: return b
    return None

  def headers(self):
    pass

  def expunge(self):
    pass

  def message_with_id(self, id):
    res = filter(lambda x, _id=id: x.id() == _id, self.messages())
    if res and len(res):
      return res[0]
    return None

  def save_message_cache(self, dir):
    p = string.replace(self.path(), '/', '.')
    #p = string.replace(p, '~', '.')
    cache_file = os.path.join(dir, p)
    cache = []
    if self._messages:
      for msg in self._messages:
        cache.append(msg.cache_value())
    f = open(cache_file, 'w')
    pickle.dump(cache, f)
    f.close()

    for box in self.mailboxes():
      box.save_message_cache(dir)

  def load_message_cache(self, dir):
    p = string.replace(self.path(), '/', '.')
    cache_file = os.path.join(dir, p)
    if os.path.exists(cache_file):
      self.debug('%s: loading cache from: %s' % (self.path(), cache_file))
      try:
        f = open(cache_file, 'r')
        cache = pickle.load(f)
        f.close()
      except:
        self.debug('%s: bad cache file, ignoring' % self.path())
        return 0

      bar = self._source._ui.start_progress('Loading message cache for %s(%s)' %
                                            (self._source.name(), self.path()),
                                            len(cache))
      
      self._messages = []
      cnt = 0
      for c in cache:
        msg = self._source.message_creator(self._source, self, c["id"])
        msg.set_cache_value(c)
        self._messages.append(msg)
        self._source._ui.update_progress(cnt, bar)
        cnt = cnt + 1
      self._source._ui.finish_progress(bar)
      return 1
    return 0
      
  def can_add_subfolder(self):
    return false

  def can_delete(self):
    return false

  def can_rename(self):
    return false

  def can_expunge(self):
    return false

  def create_subfolder(self, name):
    self._source.create_subfolder(name, self)

  def delete(self):
    self._source.delete_subfolder(self)

  def rename(self, newname):
    self._source.rename(self, newname)

  def remove(self, mailbox):
    del self._mailboxes[mailbox.name()]

  def create_mailboxes(self, path, sidx, delim, source, creator):
    self.debug('create_mailboxes: %s, %s, %s' % (path, sidx, delim))
    rest = None
    idx = string.find(path, delim, sidx)
    this_name = path[sidx:]
    this_path = path
    if idx != -1:
      this_name = path[sidx:idx]
      this_path = path[:idx]

    self.debug('looking for %s' % this_name)
    box = self._mailboxes.get(this_name)
    if not box:
      self.debug('nope, creating')
      box = creator(source, this_path, delim, self)
      self._mailboxes[box.name()] = box
    else:
      self.debug('foundit')

    if idx != -1:
      self.debug('doing the rest: %s' % path[idx+1:])
      box.create_mailboxes(path, idx+1, delim, source, creator)
      



