'''
Hello actions
'''
from __future__ import unicode_literals
from decorators import pi18n
from sqlalchemy import or_
import web

from main.model import Computer, OrganizativeUnit
from clientjob.model import Job
from clientjob.jobview import JobView

class CancelJobsView:
    @pi18n
    def GET(self, entity_type, name):
        orm = web.ctx.orm
        if entity_type == "computer":
            computer = orm.query(Computer).filter(Computer.name == name).first()
            if not computer:
                self.error(_('Computer "%s" not found') % name)
            jobs = orm.query(Job).filter(Job.computer == computer).\
                       filter(Job.id >= 1024)
            for job in jobs:
                if job.status in ('CREATED', 'WAITING'):
                    job.status = 'CANCELLED'
        elif entity_type == "ou":
            ou = orm.query(OrganizativeUnit).filter(OrganizativeUnit.name == name).first()
            if not ou:
                self.error(_('Organizative Unit "%s" not found') % name)
            computer_ids = [computer.id for computer in ou.get_all_descendants()]
            jobs = orm.query(Job).filter(Job.computer_id.in_(computer_ids)).\
                       filter(Job.status.in_(['CREATED', 'WAITING'])).\
                       filter(Job.id >= 1024).all()
            for job in jobs:
                job.status = 'CANCELLED'
        Job.update_parent_jobs_status()
        return JobView().GET()
