from newsBA import NewsBA
from help import Help
from workerThread import WorkerThread
from qt import *
from constants import EVENT_NEWS_SUBMITTED
from messageQueue import mainMessageQueue

from utf8 import to_utf8

class News(NewsBA):
    def __init__(self, parent, projectVO, sf_comm):
        NewsBA.__init__(self)
        self.parent = parent
        self.projectVO = projectVO
        self.sf_comm = sf_comm

        caption = self.caption()
        caption += ": %s" % projectVO.getProjectName()
        self.setCaption(caption)

        self.newsGroupBox.setTitle("%s: News" %
                                  projectVO.getProjectName())
        
        self.statusFrame.hide()
        self.show()
        self.eventDict = {
            EVENT_NEWS_SUBMITTED: self.news_submitted
            }


    def customEvent(self, event):
        data = event.data()
        etype = event.type()
        event_action = self.eventDict.get(etype)
        if event_action: event_action(data)
        

    def enable_ok_button(self):
        enabled = 0
        if (not self.messageTextEdit.text().isEmpty() and 
            not self.subjectLineEdit.text().isEmpty()):
            enabled = 1
            
        self.buttonOk.setEnabled(enabled)
            

    def accept(self):
        self.statusFrame.hide()
        self.submit_news()


    def submit_news(self):
        self.setCursor(Qt.waitCursor)
        groupid = self.projectVO.getGroupId()
        subject = to_utf8(self.subjectLineEdit.text())
        message = to_utf8(self.messageTextEdit.text())

        self.thread = WorkerThread(self,
                                   EVENT_NEWS_SUBMITTED,
                                   self.sf_comm.submit_news,
                                   groupid,
                                   subject,
                                   message)        
        self.thread.start()


    def news_submitted(self, ok):
        self.setCursor(Qt.arrowCursor)

        if ok:
            mainMessageQueue.put("Project news submitted successfully.")
            NewsBA.accept(self)
        else:
            self.statusTextLabel.setText("Error submitting news")
            self.statusFrame.show()



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


