#!/usr/bin/env jython

import sys
import getopt
import time

from java.awt import BorderLayout
from java.awt import GridLayout
from java.awt import Dimension

from javax.swing import JFrame
from javax.swing import JButton
from javax.swing import JLabel
from javax.swing import JTextField
from javax.swing import JButton
from javax.swing import JPanel
from javax.swing import JScrollPane
from javax.swing import JTable
from javax.swing import JTabbedPane
from javax.swing import JComboBox
from javax.swing import JOptionPane

from javax.swing.table import DefaultTableModel

from ipptopsps import IppToPsps

'''
Console class
'''
class Console(IppToPsps):

    '''
    Constructor
    '''
    def __init__(self, argv):
        super(Console, self).__init__(argv, 0, 0)
    
        self.frame = JFrame(
                "ippToPsps console for config '" + self.config.name + "'", 
                layout=BorderLayout(),
                size=(1000, 500),
                windowClosing=self.exitProgram)

        tabbedPane = JTabbedPane(JTabbedPane.TOP)
        tabbedPane.addTab("Clients", self.createClientsPanel())

        #self.label = JLabel("Some title", JLabel.CENTER)
        #self.frame.add(self.label, BorderLayout.NORTH)

        self.frame.add(tabbedPane, BorderLayout.CENTER)

    '''
    Creates a panel for managing clients
    '''
    def createClientsPanel(self):

        panel = JPanel(layout=BorderLayout())

        self.clientTable = JTable()
        scrollPane = JScrollPane()
        scrollPane.setPreferredSize(Dimension(100,125))
        scrollPane.getViewport().setView((self.clientTable))

        # side panel of buttons
        buttonPanel = JPanel(layout=GridLayout(6, 1))
        button = JButton('Pause', actionPerformed=self.pause)
        buttonPanel.add(button)
        button = JButton('Resume', actionPerformed=self.resume)
        buttonPanel.add(button)
        button = JButton('Kill', actionPerformed=self.kill)
        buttonPanel.add(button)
        button = JButton('Cancel kill', actionPerformed=self.cancelKill)
        buttonPanel.add(button)
        button = JButton('Purge dead', actionPerformed=self.purgeDead)
        buttonPanel.add(button)
        button = JButton('Change config', actionPerformed=self.changeConfig)
        buttonPanel.add(button)

        button = JButton('Refresh', actionPerformed=self.refreshClientTable)

        panel.add(scrollPane, BorderLayout.CENTER)
        panel.add(buttonPanel, BorderLayout.EAST)
        panel.add(button, BorderLayout.SOUTH)

        self.refreshClientTable(None)

        return panel

    '''
    Gets table selection
    '''
    def getSelectedIds(self):
        rows = self.clientTable.getSelectedRows()
        ids = []
        for row in rows: ids.append(self.clientDataModel.getValueAt(row, 0))
        return ids

    '''
    Refreshes clients table
    '''
    def refreshClientTable(self, event):

        clients = self.ippToPspsDb.getClientInfo()
        colNames = ('ID','host', 'started', 'timestamp', 'ra_center', 'paused?', 'killed?')
        self.clientDataModel = DefaultTableModel(clients, colNames)
        self.clientTable.setModel(self.clientDataModel)

    '''
    Overriden
    '''
    def exitProgram(self,  exitReason="quit"):

        self.frame.dispose()
        super(Console, self).exitProgram("window closed")


    '''
    Pause/kill button callbacks
    '''
    def pause(self, event): 
        self.ippToPspsDb.pauseLoaders(True, self.getSelectedIds())
        self.refreshClientTable(None)
    def resume(self, event): 
        self.ippToPspsDb.pauseLoaders(False, self.getSelectedIds())
        self.refreshClientTable(None)
    def kill(self, event): 
        self.ippToPspsDb.killLoaders(True, self.getSelectedIds())
        self.refreshClientTable(None)
    def cancelKill(self, event): 
        self.ippToPspsDb.killLoaders(False, self.getSelectedIds())
        self.refreshClientTable(None)
    def remove(self, event): 
        self.ippToPspsDb.removeClientsByIds(self.getSelectedIds())
        self.refreshClientTable(None)
    def purgeDead(self, event): 
        self.ippToPspsDb.purgeDeadClients()
        self.refreshClientTable(None)
    def changeConfig(self, event): 
        ids = self.getSelectedIds()
        if len(ids) < 1: 
            JOptionPane.showMessageDialog(None, "No clients selected", "Error", JOptionPane.ERROR_MESSAGE)
            return
        comboBox = JComboBox(self.ippToPspsDb.getActiveConfigList())
        if JOptionPane.showConfirmDialog(None, 
                comboBox, 
                "Choose a config",
                JOptionPane.OK_CANCEL_OPTION,
                JOptionPane.PLAIN_MESSAGE) == JOptionPane.CANCEL_OPTION: return

        self.ippToPspsDb.setConfigForLoaders(comboBox.getSelectedItem(), ids)
        self.refreshClientTable(None)



    '''
    Runs...
    '''
    def run(self):
        self.frame.setVisible(True)

'''
Start of program
'''
console = Console(sys.argv)
console.run()

