import re


from ..pluginbase import PluginBase
from main.model import Computer, OrganizativeUnit
from ..action import ActionInstance
import views
import web


class Plugin(PluginBase):
    '''
    Plugin to manage the booting (from shutdown to opengnsys) and shutdown of
    an entity (an ou or a computer).

    For an OU, it will always show both boot and shutdown actions, which would
    boot or shutdown all the offline computers in that OU. For a given computer,
    it will only show the boot or the shutdown action depending if the computer is
    booted or not.
    '''
    def enable(self):
        self.urls = ('boot/(computer|ou)/(.*)', views.BootView,
            'shutdown/(computer|ou)/(.*)', views.ShutdownView,
            'restart/(computer|ou)/(.*)', views.RestartView,
        )

    def get_action_instances_for_view(self, view_path, args):
        orm = web.ctx.orm
        actions = []
        if view_path == 'navigator.navigator.NavigatorComputer' and\
            len(args) > 0:
            name = args[0]
            computer = orm.query(Computer).filter(Computer.name == name).first()

            if not computer:
                return []

            actions = [
                ActionInstance(self.actions['restart'],
                    self.fill_url(views.RestartView, "computer", name)
                )
            ]
            if computer.online:
                actions += [
                    ActionInstance(self.actions['shutdown'],
                        self.fill_url(views.ShutdownView, "computer", name)
                    )
                ]
            else:
                actions += [
                    ActionInstance(self.actions['boot'],
                        self.fill_url(views.BootView, "computer", name)
                    )
                ]
        elif view_path == 'navigator.navigator.NavigatorOrganizativeUnit' and\
            len(args) > 0:

            name = args[0]
            ou = orm.query(OrganizativeUnit).filter(OrganizativeUnit.name == name).first()
            if not ou:
                return []
            actions = [
                ActionInstance(
                    self.actions['restart'],
                    self.fill_url(views.RestartView, "ou", name)
                ),
                ActionInstance(
                    self.actions['boot'],
                    self.fill_url(views.BootView, "ou", name)
                ),
                ActionInstance(
                    self.actions['shutdown'],
                    self.fill_url(views.ShutdownView, "ou", name)
                )
            ]
        return actions
