#!/usr/bin/env python

'''jobsStatus.py - Panel for handling jobs on the cluster'''

import wx
import const
from checkStatus import CheckStatus
from cancelJobs import CancelJobsWindow
from downloadWindow import DownloadWindow

from jobsGridSizer import GridTable
from sqlite3_mods import tables_dict

class HandleJobsFrame(wx.Frame):
  def __init__(self, remoteData, *args, **kwargs):
    kwargs['size'] = (1000, 1000)
    wx.Frame.__init__(self, None, -1, "Jobs Status Test Frame", *args, **kwargs)

    JobsPanel(self, remoteData, *args, **kwargs)

class JobsPanel(wx.Panel):
  '''Jobs status panel'''
  def __init__(self, parent, remoteData, *args, **kwargs):
    wx.Panel.__init__(self, parent, -1, style=wx.BORDER_SIMPLE, *args, **kwargs)

    '''check jobs status and save data to 'data.db' '''
    CheckStatus(**remoteData)

    '''initiate the main sizer'''
    self.SetSizer(JobsSizer(self, **remoteData))

class JobsSizer(wx.BoxSizer):
  '''Cluster jobs sizer'''
  def __init__(self, parent, *args, **kwargs):
    wx.BoxSizer.__init__(self, wx.VERTICAL)

    '''TITLE'''
    titleFont = wx.Font(14, wx.DEFAULT, wx.ITALIC, wx.BOLD)
    title = wx.StaticText(parent, -1, style=wx.ALIGN_LEFT,
        label='{} jobs status on {}:'.format(kwargs['login'], kwargs['hostname']))
    title.SetFont(titleFont)
    titleSizer = wx.BoxSizer(wx.HORIZONTAL)
    titleSizer.AddMany([(100, -1), (title, wx.EXPAND)])
    self.Add(titleSizer, 0, wx.ALL|wx.EXPAND, 10)

    '''JOB TABLES'''
    icon_names = {
        'ActiveJobs': 'blue', 'IdleJobs': 'yellow', 'BlockedJobs': 'red',
        'FinishedJobs': 'green', 'SubmitedJobs': 'gray'
    }
    tables_dict['SubmitedJobs'] = "pending jobs"
    for item in tables_dict:
        self.AddMany(GridTable(parent, tables_dict[item],
            icon_names[item], item, **kwargs).getGridTable())

    '''BUTTONS'''
    cancelBtn = wx.Button(parent, wx.ID_CANCEL, 'Cancel Jobs')
    dwnBtn = wx.Button(parent, wx.ID_DOWN, 'Download Jobs')
    okBtn = wx.Button(parent, wx.ID_OK)

    cancelBtn.Bind(wx.EVT_BUTTON, self.CancelJob)
    dwnBtn.Bind(wx.EVT_BUTTON, self.DownloadJob)
    okBtn.Bind(wx.EVT_BUTTON, self.OkBtn)

    btnSizer = wx.BoxSizer(wx.HORIZONTAL)
    btnSizer.AddMany([okBtn, const.hbtnSpace, dwnBtn, const.hbtnSpace, cancelBtn])

    self.AddMany([(-1, 70), (btnSizer, 0, wx.ALIGN_RIGHT|wx.ALL, 20)])

    self.parent = parent # to use in events functions
    self.remoteData = kwargs

  def CancelJob(self, evt):
    '''Cancel job on server and delete files'''
    CancelJobsWindow(**self.remoteData).Show()
    self.parent.GetParent().Close()


  def DownloadJob(self, evt):
    '''Moving files from server to client'''
    DownloadWindow(**self.remoteData).Show()
    self.parent.GetParent().Close()

  def OkBtn(self, evt):
    '''Close the window'''
    self.parent.GetParent().Close()

if __name__ == "__main__":
  from remote_data import loginInfo
  app = wx.App(False)
  HandleJobsFrame(loginInfo).Show()
  app.MainLoop()
