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

import wx


class ServicePanel(wx.Panel):
	def __init__(self, parent, service):
		wx.Panel.__init__(self, parent, wx.ID_ANY)
		self.service = service
		
		label = wx.StaticText(self, wx.ID_ANY, service.name)
		self.status = wx.StaticText(self, wx.ID_ANY, 'Service status is unknown for the moment')
		
		self.start = wx.Button(self, wx.ID_ANY, 'Start')
		self.query = wx.Button(self, wx.ID_ANY, 'Query status')
		self.stop = wx.Button(self, wx.ID_ANY, 'Stop')
		
		
		line1sz = wx.BoxSizer(wx.HORIZONTAL)
		line1sz.Add(label, 1, wx.ALL | wx.ALIGN_CENTER_VERTICAL, 5)
		line1sz.Add(self.start, 0, wx.ALL | wx.ALIGN_CENTER_VERTICAL, 5)
		line1sz.Add(self.query, 0, wx.ALL | wx.ALIGN_CENTER_VERTICAL, 5)
		line1sz.Add(self.stop, 0, wx.ALL | wx.ALIGN_CENTER_VERTICAL, 5)
	
		sizer = wx.BoxSizer(wx.VERTICAL)
		sizer.Add(line1sz, 0, wx.EXPAND | wx.ALIGN_CENTER_VERTICAL)
		sizer.Add(self.status, 0, wx.ALL | wx.EXPAND | wx.ALIGN_CENTER_VERTICAL, 5)
		self.SetSizer(sizer)
		
		self.start.Bind(wx.EVT_BUTTON, self.OnStart)
		self.query.Bind(wx.EVT_BUTTON, self.OnQuery)
		self.stop.Bind(wx.EVT_BUTTON, self.OnStop)
		
		self.update()
		
	def OnStart(self, event):
		self.status.SetLabel('Starting '+self.service.name+' ...')
		self.Disable()
		wx.Yield()
		self.service.server.smart_start_services(ids=[self.service.id])
		self.update()
		self.Enable()
	
	def OnQuery(self, event):
		self.status.SetLabel('Querying status of '+self.service.name+' ...')
		wx.Yield()
		self.update()
	
	def OnStop(self, event):
		self.status.SetLabel('Stopping '+self.service.name+' ...')
		self.Disable()
		wx.Yield()
		self.service.server.smart_stop_services(ids=[self.service.id])
		self.update()
		self.Enable()
		
	def update(self):
		running = self.service.is_running()
		if running:
			self.status.SetLabel(self.service.name+' is running')
			self.start.Enable(False)
			self.stop.Enable(True)
		else:
			self.status.SetLabel(self.service.name+' is stopped')
			self.start.Enable(True)
			self.stop.Enable(False)
	
class MainFrame(wx.Frame):
	
	def __init__(self):
		wx.Frame.__init__(self, None, wx.ID_ANY, title='PiAnoS Server Management')
	
		sizer = wx.BoxSizer(wx.VERTICAL)
		server = wx.GetApp().server
		for service in server.services:
			panel = ServicePanel(self, service)
			sizer.Add(panel, 0, wx.EXPAND)
		sizer.Add(wx.Panel(self, wx.ID_ANY), 1, wx.EXPAND)
		self.SetSizerAndFit(sizer)
	