import os, sys
from constants import ADDRESS_BOOK_FILENAME
import logging


debug = logging.getLogger("addressBook").debug
warn = logging.getLogger("addressBook").warn
error = logging.getLogger("addressBook").error

class AddressBook:
    def __init__(self, data_path, autoload=True):
        self.path = os.path.join(data_path, ADDRESS_BOOK_FILENAME)
        self.data = {}
        if autoload: self.read_file()

    def is_empty(self):
        return len(self.data.keys()) > 0


    def read_file(self):
        try:
            fp = open(self.path, "r")
            for line in fp:
                project_name, email_addr = line.split(":")
                project_name = project_name.strip()
                email_addr = email_addr.strip()
                #debug("%s: %s", project_name, email_addr)
                project_email_addrs = self.data.get(project_name, [])
                project_email_addrs.append(email_addr)
                self.data[project_name] = project_email_addrs
        except Exception, e:
            warn(e)


    def save_file(self):
        try:
            fp = open(self.path, "w")
        except Exception, e:
            error(e)
            return
        
        projects = self.data.keys()
        for project in projects:
            email_addrs = self.data[project]
            for email_addr in email_addrs:
                fp.write("%s: %s\n" % (project, email_addr))
        fp.close()

                       
    def get(self, project_name):
        addresses = self.data.get(project_name, [])
        addresses.sort()
        return addresses

        
    def set(self, project_name, email_addrs, autosave=False):
        self.data[project_name] = email_addrs
        if autosave: self.save_file()

    
