import web
from clientjob.model import Job
from user.views import get_user
from main.model import Computer
from utils import fancy_datetime


class JobView:
    '''
    Shows the list of child jobs given a parent job.

    If any of the jobs has associated any child jobs, it will show a link to show
    them.
    '''
    def GET(self, parent_id=None):
        orm = web.ctx.orm
        alljobs = orm.query(Job)
        user = get_user()
        jobs = alljobs.filter(Job.parent_id == parent_id).\
                       filter(Job.id >= 1024).order_by(Job.creation_date.desc())[0:50]
        jobs = [i for i in jobs if check_job_perm(i, user)]

        parent = alljobs.filter(Job.id == parent_id).first()

        return web.ctx.render.clientjob.list(jobs, parent, fancy_datetime)


def check_job_perm(job, user):
    if user.super_user:
        return True

    comp = job.computer
    if not comp:
        comps = job.children
        if not comps:
            return False
        return reduce(lambda x, y: x and y, [check_permissions(i, user) for i in comps])
    else:
        return check_permissions(comp, user)


def check_permissions(item, user):
    if item.__class__.__name__ == "OrganizativeUnit":
        if item.parent_id == None and not item in user.organizative_units:
            return False
        elif item in user.organizative_units:
            return True
        else:
            return check_permissions(item.parent, user)
    else:
        return check_permissions(item.ou, user)
