def list(request):
    """brands list """
    search = request.params.get("search", "")

    sort = "name"
    if request.GET.get("sort") and request.GET.get("sort") == "name":
        sort = request.GET.get("sort")

    direction = "asc"
    if request.GET.get("direction") and request.GET.get("direction") in ["asc", "desc"]:
        direction = request.GET.get("direction")

    # db query
    dbsession = DBSession()
    query = dbsession.query(Brand).filter(Brand.name.like(search + "%")).order_by(sort + " " + direction)

    # paginate
    page_url = paginate.PageURL_WebOb(request)
    brands = Page(query, page=int(request.params.get("page", 1)), items_per_page=10, url=page_url)

    if "partial" in request.params:
        # Render the partial list page
        return render_to_response("brand/listPartial.html", {"brands": brands}, request=request)
    else:
        # Render the full list page
        return render_to_response("brand/list.html", {"brands": brands}, request=request)
def get_brands():
    """Gets all brands with id, name value pairs """
    dbsession = DBSession()
    brands_q = dbsession.query(Brand).order_by(Brand.name)
    brands = [(brand.id, brand.name) for brand in brands_q.all()]
    
    return brands
def edit(request):
    """device edit """
    id = request.matchdict['id']
    dbsession = DBSession()
    device = dbsession.query(Device).filter_by(id=id).one()
    if device is None:
        request.session.flash("error;No se encontro el dispositivo!")
        return HTTPFound(location=request.route_url("device_list"))        
    

    form = Form(request, schema=DeviceForm)    
    if "form_submitted" in request.POST and form.validate():
        form.bind(device)
        dbsession.add(device)
        request.session.flash("warning;Se guardo el dispositivo!")
        s = SuperControl()
	s.restart('condor')
	return HTTPFound(location = request.route_url("device_list"))

    storage = request.registry.settings['storage']
    sp = path.join(storage, str(device.id))
    last = max(glob.iglob(path.join(sp, '*.png')), key=path.getctime)
    sample = '/store/{0}/{1}'.format(device.id, path.split(last)[1])
    action_url = request.route_url("device_edit", id=id)
    if device.roi is None: device.roi = '400,400,650,650'
    return dict(form=FormRenderer(form), 
                action_url=action_url, obj=device,sample = sample )
def list(request):
    s=request.session
    if 'logts' not in s:
        s['logts'] =datetime.min

    query = DBSession.query(PlateLog).join(Plate).filter(PlateLog.timestamp>s['logts']).order_by("logs.id desc").all()

    if len(query):
        s['logts'] = query[0].timestamp

    return query
def edit(request):
    """brand edit """
    id = request.matchdict["id"]
    dbsession = DBSession()
    brand = dbsession.query(Brand).filter_by(id=id).one()
    if brand is None:
        request.session.flash("error;No se encontro la marca!")
        return HTTPFound(location=request.route_url("brand_list"))

    form = Form(request, schema=BrandForm, obj=brand)
    if "form_submitted" in request.POST and form.validate():
        form.bind(brand)
        dbsession.add(brand)
        request.session.flash("warning;Se guardo la marca!")
        return HTTPFound(location=request.route_url("brand_list"))

    action_url = request.route_url("brand_edit", id=id)
    return dict(form=FormRenderer(form), action_url=action_url)
def new(request):
    """new plate """
    brands = get_brands()
    
    form = Form(request, schema=PlateForm)    
    if "form_submitted" in request.POST and form.validate():
        dbsession = DBSession()
        plate = form.bind(Plate())
        existing = dbsession.query(Plate).filter_by(code=plate.code).count()
        if not existing:
            dbsession.add(plate)
            request.session.flash("warning;Nueva Patente guardada!")
        else:
            request.session.flash("error; Ya existe la patente!")
        return HTTPFound(location = request.route_url("plate_list"))
        
    return dict(form=FormRenderer(form),
                brands=brands, 
                action_url=request.route_url("plate_new"))
def delete(request):
    """plate delete """
    id = request.matchdict['id']
    dbsession = DBSession()
    plate = dbsession.query(Plate).filter_by(id=id).first()
    if plate is None:
        request.session.flash("error;Patente no encontrada!")
        return HTTPFound(location=request.route_url("plate_list"))        
    
    try:
        transaction.begin()
        dbsession.delete(plate);
        transaction.commit()
        request.session.flash("warning;Se elimino la patente!")
    except IntegrityError:
        # delete error
        transaction.abort()
        request.session.flash("error;La patente no se pudo eliminar!")
    
    return HTTPFound(location=request.route_url("plate_list"))
def delete(request):
    """device delete """
    id = request.matchdict['id']
    dbsession = DBSession()
    device = dbsession.query(Device).filter_by(id=id).first()
    if device is None:
        request.session.flash("error;No se encontro el dispositivo!")
        return HTTPFound(location=request.route_url("device_list"))        
    
    try:
        transaction.begin()
        dbsession.delete(device);
        transaction.commit()
        request.session.flash("warning;Se elimino el dispositivo!")
    except IntegrityError:
        # delete error
        transaction.abort()
        request.session.flash("error;No se pudo eliminar el dispositivo!")
    
    return HTTPFound(location=request.route_url("device_list"))
def delete(request):
    """brand delete """
    id = request.matchdict["id"]
    dbsession = DBSession()
    brand = dbsession.query(Brand).filter_by(id=id).first()
    if brand is None:
        request.session.flash("error;Marca inexistente!")
        return HTTPFound(location=request.route_url("brand_list"))

    try:
        transaction.begin()
        dbsession.delete(brand)
        transaction.commit()
        request.session.flash("warning;Marca inexistente!")
    except IntegrityError:
        # delete error
        transaction.abort()
        request.session.flash(
            "error;No se pudo eliminar la marca. Verifique que no este siendo usada por ningun registro!"
        )

    return HTTPFound(location=request.route_url("brand_list"))
def edit(request):
    """plate edit """
    id = request.matchdict['id']
    dbsession = DBSession()
    plate = dbsession.query(Plate).filter_by(id=id).first()
    if plate is None:
        request.session.flash("error;Patente no encontrada!")
        return HTTPFound(location=request.route_url("plate_list"))        
    
    brands = get_brands()
    
    form = Form(request, schema=PlateForm, obj=plate)    
    if "form_submitted" in request.POST and form.validate():
        form.bind(plate)
        dbsession.add(plate)
        request.session.flash("warning;Se guardo la patente!")
        return HTTPFound(location = request.route_url("plate_list"))

    action_url = request.route_url("plate_edit", id=id)
    return dict(form=FormRenderer(form),
                brands=brands, 
                action_url=action_url)