Source

miuler-mocksmtp / src / main / scala / com / miuler / mocksmtp / gui / MainGUI.scala

package com.miuler.mocksmtp.gui

import java.util.Properties
import java.io.{ByteArrayOutputStream, InputStreamReader, BufferedReader, ByteArrayInputStream}
import javax.mail.Session
import javax.mail.internet.MimeMessage
import collection.mutable.ListBuffer
import org.joda.time.DateTime
import org.slf4j.LoggerFactory
import com.miuler.mocksmtp.core.MockSMTP
import com.miuler.mocksmtp.utils.Utils.showMessageE
import com.trolltech.qt.QThread
import com.trolltech.qt.core.Qt.ConnectionType
import com.trolltech.qt.gui.QSystemTrayIcon.ActivationReason
//     com.trolltech.qt.gui.QSystemTrayIcon$ActivationReason
//                          QSystemTrayIcon::ActivationReason
import com.trolltech.qt.gui.QPalette.ColorRole
import com.trolltech.qt.core.{QModelIndex, Qt}
import com.trolltech.qt.gui._

/**
 * Created with IntelliJ IDEA.
 * User: miuler
 * Date: 13/09/12
 * Time: 08:16 PM
 * To change this template use File | Settings | File Templates.
 */
class MainGUI(id: String = null, serverId: String = null) {
  QApplication.initialize(Array[String]())
  new MainWindowSMTP()
  QApplication.exec()
}

/**
 * Created with IntelliJ IDEA.
 * User: miuler
 * Date: 13/09/12
 * Time: 08:16 PM
 * To change this template use File | Settings | File Templates.
 */
class MainWindowSMTP(id: String = null, serverId: String = null) extends QWidget {

  private val log = LoggerFactory.getLogger(classOf[MainGUI])
  private val session = Session.getInstance(new Properties)
  private val emails = ListBuffer[MimeMessage]()
  private val lcd = new QLCDNumber()
  private val btnInitSMTP: QPushButton = new QPushButton()
  private val btnStopSMTP: QPushButton = new QPushButton()
  private val treeView = new QTreeView
  private var model: QStandardItemModel = _
  private val systray = new QSystemTrayIcon(this)

  private var mockSMTP: MockSMTP = _
  private val connectionTheadNetty = new QConnectionThreadNetty
  private var threadConnectionThreadNetty = new QThread (connectionTheadNetty)

  initGUI
  initConnectionThread

  private def initGUI {
    // =========================================================================
    btnInitSMTP.setCheckable(true)
    btnInitSMTP.setText("Iniciar servidor SMTP")
    btnInitSMTP.toggled.connect(this, "onStartSMTP()")

    btnStopSMTP.setCheckable(true)
    btnStopSMTP.setText("Parar servidor SMTP")
    btnStopSMTP.toggle()
    btnStopSMTP.setDisabled(true)
    btnStopSMTP.toggled.connect(this, "onStopSMTP()")

    val btnClean = new QPushButton("Borrar correos")
    btnClean.clicked.connect(this, "onCleanEmails()")
    // =========================================================================

    // =========================================================================
    //lcd.setDigitCount(3)
    lcd.setBackgroundRole(ColorRole.Dark)
    // =========================================================================

    // =========================================================================
    systray.setToolTip("Servidor mock de correos")
    log.debug("isNull: {}", (new QPixmap("classpath:smtp_server_16x16_off.png")).isNull)
    systray.setIcon(new QIcon(new QPixmap("classpath:smtp_server_16x16_off.png")))
    systray.activated.connect(this, "onActivated(com.trolltech.qt.gui.QSystemTrayIcon$ActivationReason)");
    systray.show()
    // =========================================================================

    // =========================================================================
    model = new QStandardItemModel(0, 5, this)
    model.setHeaderData(0, Qt.Orientation.Horizontal, tr("id"))
    model.setHeaderData(1, Qt.Orientation.Horizontal, tr("Fecha de envio"))
    model.setHeaderData(2, Qt.Orientation.Horizontal, tr("Asunto"))

    var standardItem = new QStandardItem()
    standardItem.setEditable(false)
    model.setItemPrototype(standardItem)
    treeView.setRootIsDecorated(false)
    treeView.setAlternatingRowColors(true)
    treeView.setModel(model)
    treeView.setSortingEnabled(true)
    treeView.sortByColumn(0, Qt.SortOrder.AscendingOrder)
    treeView.setMinimumSize(300, 200) //TODO: @Miuler: Esto es para evitar un error en algunas maquinas
    treeView.resize(300, 200)
    treeView.doubleClicked.connect(this, "onViewEmail(com.trolltech.qt.core.QModelIndex)")
    treeView.hideColumn(3)
    treeView.hideColumn(4)
    // =========================================================================

    // =========================================================================
    val hlayout = new QHBoxLayout()
    hlayout.addWidget(btnInitSMTP)
    hlayout.addWidget(btnStopSMTP)
    hlayout.addWidget(btnClean)
    hlayout.addWidget(lcd)
    // =========================================================================

    // =========================================================================
    val vlayout = new QVBoxLayout()
    vlayout.addItem(hlayout)
    vlayout.addWidget(treeView)
    setLayout(vlayout)
    setWindowTitle("MOCK SMTP")
    resize(320, 240)
    show()
    // =========================================================================
  }

  def initConnectionThread {
    connectionTheadNetty.moveToThread(threadConnectionThreadNetty)
    connectionTheadNetty.messageSignal.connect(this, "addEmail(String)", ConnectionType.QueuedConnection)
    threadConnectionThreadNetty.start
    mockSMTP = new MockSMTP(connectionTheadNetty)
  }

  def onStartSMTP() {
    try {
      if (btnInitSMTP.isChecked()) {
        mockSMTP.start
        btnInitSMTP.setDisabled(true)
        btnStopSMTP.toggle()
        btnStopSMTP.setDisabled(false)
        lcd.setBackgroundRole(ColorRole.Light)
        systray.setIcon(new QIcon(new QPixmap("classpath:smtp_server_16x16.png")))
      }
    } catch {
      case e: Exception => {
        log.error("Error al iniciar servidor SMTP", e)
        showMessageE(e)
      }
    }
  }

  def onStopSMTP() {
    if (btnStopSMTP.isChecked()) {
      mockSMTP.stop
      btnInitSMTP.setDisabled(false)
      btnInitSMTP.toggle()
      btnStopSMTP.setDisabled(true)
      lcd.setBackgroundRole(ColorRole.Dark)
      systray.setIcon(new QIcon(new QPixmap("classpath:smtp_server_16x16_off.png")))
    }
  }

  override def closeEvent(evn: QCloseEvent) {
    log.debug("systray.isVisible: {}", systray.isVisible)
    log.debug("salir")
    if (btnInitSMTP.isChecked()) {
      log.debug("Apagando el servidor")
      mockSMTP.stop
    }
    if (threadConnectionThreadNetty.isAlive) {
      connectionTheadNetty.loopConnectionNetty = false
      connectionTheadNetty.msg = null
      connectionTheadNetty.mutex.unlock
    }
    super.closeEvent(evn)
  }

  def addEmail(msg: String) {
    if (msg!=null & msg!="") {
      val email = new MimeMessage(session, new ByteArrayInputStream(msg.getBytes()))
      val date = new DateTime()

      systray.showMessage("LLego un correo", email.getSubject)

      emails.append(email)
      model.insertRow(0)
      model.setData(model.index(0, 0), model.rowCount())
      //model.setData(model.index(0, 1), DateTimeFormat.forPattern("M-dd HH:mm").print(date))
      model.setData(model.index(0, 1), date.toString("M-dd HH:mm"))
      model.setData(model.index(0, 2), email.getSubject())
      model.setData(model.index(0, 3), date)
      model.setData(model.index(0, 4), email)
      lcd.display(model.rowCount())
    }
  }

  def onCleanEmails() {
    emails.clear
    model.removeRows(0, model.rowCount)
    lcd.display(0)
  }

  def onActivated(reason: ActivationReason) {
    println("reason: ", reason)
    println("reason.value: ", reason.value)
    if (reason.value == 3) {
      if (this.isHidden) this.show() else
        this.hide()
    } else if (reason.value == 1) {
      //mostrar menu
    }
  }

  def onViewEmail(modelIndex: QModelIndex) {
    val email = model.data(modelIndex.row, 4).asInstanceOf[MimeMessage]
    val out = new ByteArrayOutputStream
    email.writeTo(out)

    val text = new QTextEdit
    text.setText(out.toString)

    val vlayout = new QVBoxLayout
    vlayout.addWidget(text)

    val windowEmail = new QWidget()
    windowEmail.setWindowTitle("EMAIL: " + email.getSubject)
    windowEmail.setMinimumSize(650, 500) //TODO: @Miuler: Esto es para evitar un error en algunas maquinas
    windowEmail.resize(650, 500)
    windowEmail.setLayout(vlayout)
    windowEmail.show()
  }

}