#!/usr/bin/python
# -*- coding: utf-8 -*-

"""
    Software magement module
"""

# Standard modules
import simplejson

# Qt4 modules
from PyQt4 import QtGui
from PyQt4 import QtCore

# Generated UI module
from ui_services import Ui_widgetServices

# Helper modules
from lider.helpers import plugins
from lider.helpers import wrappers

# COMAR
import comar

class WidgetModule(QtGui.QWidget, Ui_widgetServices, plugins.PluginWidget):
    """
        Software management UI.
    """
    def __init__(self, parent=None):
        """
            Constructor for main window.

            Arguments:
                parent: Parent object
        """
        plugins.PluginWidget.__init__(self)
        QtGui.QWidget.__init__(self, parent)
       
        self.link = comar.Link()

        # Attach generated UI
        self.setupUi(self)

        # UI events
        self.connect(self.pushStart, QtCore.SIGNAL("clicked()"), self.__slot_start_service)
        self.connect(self.pushStop, QtCore.SIGNAL("clicked()"), self.__slot_stop_service)
        self.connect(self.lineSearch, QtCore.SIGNAL('textChanged(const QString &)'), self.__slotSearch)


    def showEvent(self, event):
        """
            Things to do before widget is shown.
        """
        jid = "%s@%s" % (self.item.name, self.talk.domain)
        self.talk.send_command(jid, "service.info")


    def get_type(self):
        """
            Widget type.

            Should return TYPE_GLOBAL or TYPE_SINGLE
        """
        return plugins.TYPE_SINGLE

    def load_policy(self, policy):
        """
            Main window calls this method when policy is fetched from directory.
            Not required for global widgets.
        """
        pass

    def dump_policy(self):
        """
            Main window calls this method to get policy generated by UI.
            Not required for global widgets.
        """
        policy = {
        }
        return policy

 
    def talk_message(self, sender, command, arguments=None):
        """
            Main window calls this method when an XMPP message is received.
        """
        print command, arguments
        if command == "service.info":
            self.tableWidget.clear()
            row = 0
            for name, desc, status in arguments:
                row = row+1
            
            self.tableWidget.setRowCount(row)

            index = 0;
            for name, desc, status in arguments:
                nameItem = QtGui.QTableWidgetItem(str(name))
                self.tableWidget.setItem(index, 0, nameItem)

                statusItem = QtGui.QTableWidgetItem(str(status))
                self.tableWidget.setItem(index, 1, statusItem)

                if status in ['stopped', 'on']:
                    autoItem = QtGui.QTableWidgetItem("Yes")
                    self.tableWidget.setItem(index, 2, autoItem)
                elif status in ['conditional_started', 'conditional_stopped']:
                    autoItem = QtGui.QTableWidgetItem("Conditional")
                    self.tableWidget.setItem(index, 2, autoItem)
                else:
                    autoItem = QtGui.QTableWidgetItem("No")
                    self.tableWidget.setItem(index, 2, autoItem)
                
                descItem = QtGui.QTableWidgetItem(str(desc))
                self.tableWidget.setItem(index, 3, descItem)

                index = index+1

    def talk_status(self, sender, status):
        """
            Main window calls this method when an XMPP status is changed.
        """
        pass

  
    def __slot_start_service(self):
        """
            This method is called when the start button clicked to start the selected service
        """
        item = self.tableWidget.selectedItems()
        self.pushStart.setEnabled(False)
        self.link.System.Service[str(item[0].text())].start()


    def __slot_stop_service(self):
        """
            This method is called when the stop button clicked to stop the selected service
        """
        item = self.tableWidget.selectedItems()
        if item[0].type != 'server' and not self.confirmStop():
            return
        self.pushStop.setEnabled(False)
        self.link.System.Service[str(item[0].text())].stop()

    def confirmStop(self):
        msg = str('If you stop this service, you may have problems.\nAre you sure you want to stop this service?')
        reply = QtGui.QMessageBox.question(self, str('Warning'), msg,  QtGui.QMessageBox.Yes, QtGui.QMessageBox.No )

        if reply == QtGui.QMessageBox.Yes:
            self.link.System.Service[str(item[0].text())].stop()
        else:
            pass

    
    def __slotSearch(self, text):
        index = 0
        found = ''
        while index < self.tableWidget.rowCount():
            item = self.tableWidget.item(index, 0)
            index = index+1
            if(item.text() == self.lineSearch.text()):
                found = item.text()
                item.setSelected(True) 
                print "Found %s " %found
