from main.model import Computer
from clientjob.model import Job

import web
from web import form

from decorators import pi18n


class CommandJob(Job):
    def get_user_message(self):
        userm = super(CommandJob, self).get_user_message()

        m = '''
        <h3>%s</h3>
        <h4>%s</h4>
        <pre class="message">%s</pre>
        ''' % ("Message detail",
               self.command_str(), userm)

        return m


class Command:
    def getform(self, c=''):
        f = form.Form(
                form.Textbox('command',
                             form.notnull,
                             description='opengnsys@%s #' % c)
        )
        if not c:
            f.inputs += (form.Textbox('computer', form.notnull, description='computer'), )

        return f

    def GET(self, computer=''):
        return web.ctx.render.plugins.command.sendcommand(self.getform(computer))

    def POST(self, computer=''):
        f = self.getform(computer)
        if f.validates():
            if not computer:
                computer = f.computer.value
            command = f.command.value.split(" ")
            comp = web.ctx.orm.query(Computer).filter(Computer.name == computer).one()
            cjob = CommandJob(command[0], command[1:])
            cjob.computer = comp

            web.ctx.orm.add(cjob)
            web.ctx.orm.commit()

            cjob.send()
            raise web.seeother('/jobs/%s' % cjob.id)
        else:
            return web.ctx.render.plugins.command.sendcommand(f)
