from emailAnnouncementBA import EmailAnnouncementBA
from constants import *
from qt import *
import logging
import smtplib
import time
from workerThread import WorkerThread
from help import Help
from utf8 import from_utf8, to_utf8


debug = logging.getLogger("emailAnnouncement").debug
error = logging.getLogger("emailAnnouncement").error

class EmailAnnouncement(EmailAnnouncementBA):
    def __init__(self, parent, settings, address_book, projectVO):
        EmailAnnouncementBA.__init__(self, parent)
        self.settings = settings
        self.address_book = address_book
        self.projectVO = projectVO
        self.project_name = projectVO.getProjectName()
        self.email_address = settings['email_address']
        self.smtp_server = settings['smtp_server']
        self.recipient_index = 0
        self.recipients = []
        self.populateAddresses()
        self.fromTextLabel.setText(self.email_address)

        self.timer = QTimer(self)
        self.connect(self.timer, SIGNAL("timeout()"),
                     self.addressSelected)
        self.timer.start(500, False)

        self.eventDict = {EVENT_SEND_EMAIL: self.send_email}
        
        self.setNextEnabled(self.page(EMAIL_PAGE_SELECT), False)
        self.setNextEnabled(self.page(EMAIL_PAGE_CONFIRM), True)
        self.addressListBox.setFocus()
        

    def customEvent(self, event):
        data = event.data()
        etype = event.type()
        #print etype
        event_action = self.eventDict.get(etype)
        if event_action: event_action(data)
            
        
    def populateAddresses(self):
        addresses = self.address_book.get(self.project_name)
        for address in addresses:
            self.addressListBox.insertItem(address)


    def selectAll(self):
        self.addressListBox.selectAll(True)
        self.setNextEnabled(self.page(EMAIL_PAGE_SELECT), True)
        

    def addressSelected(self, qitem=None):
        enable = False

        if qitem and self.addressListBox.isSelected(qitem):
            enable = True

        if not enable:
            for i in range(self.addressListBox.numRows()):
                if self.addressListBox.isSelected(i):
                    enable = True
                    break
        #debug("enable next: %s", enable)
        self.setNextEnabled(self.page(EMAIL_PAGE_SELECT), enable)


    def back(self):
        EmailAnnouncementBA.back(self)
        self.nextButton().setText("Next")
        if self.indexOf(self.currentPage()) == EMAIL_PAGE_SELECT:
            self.timer.start(500, False)
        else:
            self.timer.stop()

        if self.indexOf(self.currentPage()) == EMAIL_PAGE_CONFIRM:
            self.nextButton().setText("Send")

    def next(self):
        self.timer.stop()
        EmailAnnouncementBA.next(self)
        pageno = self.indexOf(self.currentPage())

        #debug("pageno: %d", pageno)
        
        self.nextButton().setText("Next")
        if pageno == EMAIL_PAGE_CONFIRM:
            self.nextButton().setText("Send")
            self.populateConfirmPage()
        elif pageno == EMAIL_PAGE_COMPOSE:
            self.messageEdited()
        elif pageno == EMAIL_PAGE_PROGRESS:
            self.start_delivery()


    def start_delivery(self):
        self.progressBar.setProgress(-1)
        try:
            self.server = smtplib.SMTP(self.smtp_server)
        except Exception, e:
            QMessageBox.warning(None,
                                "An exception occurred connecting to smtp server",
                                str(e))
            return 
        self.recipients = self.get_addresses()
        self.progressBar.setTotalSteps(len(self.recipients))
        self.send_email()
    

    def end_delivery(self):
        self.recipient_index = 0
        self.setFinishEnabled(self.page(EMAIL_PAGE_PROGRESS), True)
        try:
            self.server.quit()
        except:
            pass


    def messageEdited(self, qtext=None):
        message = to_utf8(self.messageTextEdit.text())
        subject = to_utf8(self.subjectLineEdit.text())
        if message and subject:
            enable = True
        else:
            enable = False
        self.setNextEnabled(self.page(EMAIL_PAGE_COMPOSE), enable)


    def populateConfirmPage(self):
        self.confirmTextEdit.setText(self.messageTextEdit.text())
        self.confirmSubjectLineEdit.setText(self.subjectLineEdit.text())
        self.confirmListBox.clear()
        
        for i in range(self.addressListBox.numRows()):
            if self.addressListBox.isSelected(i):
                self.confirmListBox.insertItem(self.addressListBox.text(i))

        self.backButton().setFocus()


    def get_addresses(self):
        addresses = []
        for i in range(self.confirmListBox.numRows()):
            addresses.append(to_utf8(self.confirmListBox.text(i)))
        return addresses


    def email_thread(self, index):
        to_address = self.recipients[index]
        msg = "From: %s\nTo: %s\nDate: %s\nSubject: %s\n\n%s\n" % (
            self.email_address,
            to_address,
            time.strftime("%a, %d %b %Y %H:%M:%S %Z"),
            to_utf8(self.subjectLineEdit.text()),
            to_utf8(self.messageTextEdit.text()))
        
        try:
            self.server.sendmail(self.email_address, [to_address], msg)
        except Exception, e:
            QMessageBox.warning(None,
                                "An exception occurred sending email message",
                                str(e))
        return index + 1


    def send_email(self, index=0):
        self.recipient_index = index
        if self.recipient_index >= len(self.recipients):
            self.end_delivery()
            return
        
        self.recipientTextLabel.setText(self.recipients[self.recipient_index])
        self.progressBar.setProgress(self.recipient_index + 1)

        self.thread = WorkerThread(self,
                                   EVENT_SEND_EMAIL,
                                   self.email_thread,
                                   self.recipient_index)        
        self.thread.start()


    def accept(self):
        EmailAnnouncementBA.accept(self)
        
    def help(self):
        self._help = Help(self, "email_announcement.html")     
