#encoding:utf-8
'''
Created on Feb 9, 2015

@author: root
'''
from PyQt4.QtCore import QTimer, SIGNAL
from PyQt4.QtGui import QPushButton, QHBoxLayout, QVBoxLayout

from base.basedialog import BaseDialog


class TimerMessageBox(BaseDialog):
    '''
    This message box will show for 5 seconds in default and then destroy automatically
    '''


    def __init__(self, content):
        '''
        Constructor
        '''
        super(TimerMessageBox, self).__init__()
        self.message = self.hintInfo = content
        self.timeout = 5
        self.timer = QTimer()
        self.timer.setSingleShot(True)
        self.connect(self.timer, SIGNAL("timeout()"), self.onUpdateMessage)
        self.setFixedSize(480, 200)
                           
        self.setStyleSheet("QPushButton{background:url(../images/button.png);font-size: 10pt;border:2px;}")

        self.setWindowTitle(u'提示信息')
        self.setTitle(u'提示信息')
        
        self.ensureBtn = QPushButton(u'确定')
        self.ensureBtn.setFixedSize(75,27)
        self.ensureBtn.setFlat(True)
        self.ensureBtn.setDefault(True)
        self.cancelBtn = QPushButton(u'取消')
        self.cancelBtn.setFixedSize(75,27)
        self.cancelBtn.setFlat(True)
        
        
        bottomHLayout = QHBoxLayout()
        bottomHLayout.addStretch()
        bottomHLayout.addWidget(self.ensureBtn)
        bottomHLayout.addSpacing(10)
        bottomHLayout.addWidget(self.cancelBtn)
        bottomHLayout.addStretch()
        
        mainVLayout = QVBoxLayout()
        mainVLayout.addStretch()
        mainVLayout.addStretch()
        mainVLayout.addLayout(bottomHLayout)
        self.setLayout(mainVLayout)
        self.connect(self.ensureBtn, SIGNAL("clicked()"),self.slotOk)
        self.connect(self.cancelBtn, SIGNAL("clicked()"),self.slotCancel)
        
    def slotOk(self):
        self.timer.stop()
        self.timer.deleteLater()
        self.accept()
        
    def slotCancel(self):
        self.timer.stop()
        self.timer.deleteLater()
        self.reject()
        
    def updateMessage(self, message):
        self.message = message
    
    def onUpdateMessage(self):
        message = self.message + (' (%ds)' % self.timeout)
        self.hintInfo = message
        self.update()
        self.updateGeometry()
        self.timeout -= 1
        if self.timeout > 0:
            self.setTimer(self.timeout)
        else:
            print ('over')
            self.accept()
    
    def setTimer(self, timeout=5):
        self.timeout = timeout
        self.timer.start(1000)
        
    def update(self):
        super(TimerMessageBox, self).update()
    
    
    def show(self):
        self.hintInfo = self.message + (' (%ds)' % self.timeout)
        self.setTimer(self.timeout)
        return self.exec_()

