from qt import *
from emailSetupBA import EmailSetupBA
import re
from help import Help

try:
    set = set
except:
    from sets import Set
    set = Set

email_rx = re.compile('''.*?@.*?\..+?''')

class EmailSetup(EmailSetupBA):
    def __init__(self, parent, address_book, projectVO):
        EmailSetupBA.__init__(self, parent)
        self.parent = parent
        self.address_book = address_book
        self.projectVO = projectVO
        self.project_name = projectVO.getProjectName()
        self.projectNameTextLabel.setText(self.project_name)
        self.dirty = False
        self.populate()
        

    def populate(self):
        addresses = self.address_book.get(self.project_name)
        #print "addresses: ", addresses
        
        for address in addresses:
            self.addressListBox.insertItem(address)
            

    def add(self):
        self.addressListBox.insertItem(self.addressLineEdit.text())
        self.addressLineEdit.setText("")
        self.dirty = True


    def remove(self):
        text = str(self.addressListBox.currentText())
        self.addressListBox.removeItem(self.addressListBox.currentItem())
        self.removePushButton.setEnabled(False)
        self.addressLineEdit.setText(text)
        self.addressLineEdit.setFocus()
        self.dirty = True


    def address_edited(self, qaddress):
        address = str(qaddress)

        if email_rx.match(address): enable = True
        else: enable = False

        self.addPushButton.setEnabled(enable)

        
    def address_selected(self, qaddress):
        address = str(qaddress)

        if address: enable = True
        else: enable = False
            
        self.removePushButton.setEnabled(enable)

        
    def accept(self):
        if self.dirty:
            rows = self.addressListBox.numRows()
            addresses = set()

            for i in range(rows):
                address = str(self.addressListBox.text(i))
                addresses.add(address)
            
            self.address_book.set(self.project_name, list(addresses))
            self.address_book.save_file()
            self.parent.emit(PYSIGNAL("address_book_changed()"), (True, ))
        EmailSetupBA.accept(self)

        
    def help(self):
        self._help = Help(self, "email_setup.html")     
