def index():
    """
    Function to return a page listing all categories and most recent items.
    """

    set_redirect_url()

    show_all = True if request.method == 'GET' and\
        str(request.args.get('show_all', False)).lower() == 'true'\
        else False
    categories = get_all_objects_of_type(Category)
    if not show_all:
        latest_items = get_last_x_items_of_type(10, CategoryItem)
        num_items = latest_items.count()
    else:
        latest_items = get_all_objects_of_type(CategoryItem)
        latest_items.reverse()
        num_items = len(latest_items)
    user = get_user()
    items = get_all_items()

    return render_template('home.html',
                           show_all=show_all,
                           categories=categories,
                           items=items,
                           latest_items=latest_items,
                           num_items=num_items,
                           user=user)
def index():
    """
    Function to return a page listing all categories and most recent items.
    """

    set_redirect_url()

    show_all = True if request.method == 'GET' and\
        str(request.args.get('show_all', False)).lower() == 'true'\
        else False
    categories = get_all_objects_of_type(Category)
    if not show_all:
        latest_items = get_last_x_items_of_type(10, CategoryItem)
        num_items = latest_items.count()
    else:
        latest_items = get_all_objects_of_type(CategoryItem)
        latest_items.reverse()
        num_items = len(latest_items)
    user = get_user()
    items = get_all_items()

    return render_template('home.html',
                           show_all=show_all,
                           categories=categories,
                           items=items,
                           latest_items=latest_items,
                           num_items=num_items,
                           user=user)
def categories_json():
    """
    Function to return JSON of all categories.
    """

    categories = get_all_objects_of_type(Category)
    return jsonify(categories=[cat.serialize for cat in categories])
def category_info(category_id):
    """
    Function to return a page to view items for specified category.

    Args:
        category_id: ID value of the category to view.
    """

    set_redirect_url()

    # Retrieve Category object for template rendering.
    # If not found, render error template.
    category = db_session.query(Category)\
        .filter_by(id=category_id)\
        .first()
    if not category:
        return render_template(
            'error.html',
            headline_text='Category Not Found',
            error_text='The specified category was not found.')

    login_session['last_category_id'] = category.id
    category_items = db_session.query(CategoryItem).filter_by(
        category_id=category.id).all()
    creator = category.user
    user = get_user()

    return render_template('category_info.html',
                           categories=get_all_objects_of_type(Category),
                           category=category,
                           category_items=category_items,
                           creator=creator,
                           items=get_all_items(),
                           user=user)
def category_item_info(item_id):
    """
    Function to return a page to view a category item.

    Args:
        item_id: ID value of the category item to view.
    """

    set_redirect_url()

    # Retrieve CategoryItem object for template rendering.
    # If not found, render error template.
    category_item = db_session.query(CategoryItem)\
        .filter_by(id=item_id)\
        .first()
    if not category_item:
        return render_template('error.html',
                               headline_text='Item Not Found',
                               error_text='The specified item was not found.')

    creator = category_item.user
    user = get_user()

    return render_template('category_item_info.html',
                           categories=get_all_objects_of_type(Category),
                           category=category_item.category,
                           item=category_item,
                           items=get_all_items(),
                           creator=creator,
                           user=user)
def categories_json():
    """
    Function to return JSON of all categories.
    """

    categories = get_all_objects_of_type(Category)
    return jsonify(categories=[cat.serialize for cat in categories])
def category_info(category_id):
    """
    Function to return a page to view items for specified category.

    Args:
        category_id: ID value of the category to view.
    """

    set_redirect_url()

    # Retrieve Category object for template rendering.
    # If not found, render error template.
    category = db_session.query(Category)\
        .filter_by(id=category_id)\
        .first()
    if not category:
        return render_template('error.html',
                               headline_text='Category Not Found',
                               error_text='The specified category was not found.')

    login_session['last_category_id'] = category.id
    category_items = db_session.query(CategoryItem).filter_by(category_id=category.id).all()
    creator = category.user
    user = get_user()

    return render_template('category_info.html',
                           categories=get_all_objects_of_type(Category),
                           category=category,
                           category_items=category_items,
                           creator=creator,
                           items=get_all_items(),
                           user=user)
def new_category_item():
    """
    Function to return a page to create a new category item.
    """

    set_redirect_url()

    user = get_user()
    categories = get_all_objects_of_type(Category)
    category = None
    if not user:
        return redirect(url_for('login'))
    if request.method == 'POST':
        if request.form.get('name', '') == '' and request.form.get('category', '') != '':
            category = db_session.query(Category)\
                .filter_by(id=request.form.get('category'))\
                .first()
            return render_template('new_category_item.html',
                                   user=user,
                                   category=category,
                                   categories=categories,
                                   request=request)
        new_item = CategoryItem(name=request.form['name'],
                                user_id=login_session['user_id'],
                                description=request.form['description'],
                                category_id=request.form['category'])
        db_session.add(new_item)
        db_session.commit()
        flash('New Item {} Successfully Created!'.format(new_item.name))
        return redirect(url_for('index'))
    else:
        return render_template('new_category_item.html',
                               user=user,
                               category=category,
                               categories=categories)
def category_item_info(item_id):
    """
    Function to return a page to view a category item.

    Args:
        item_id: ID value of the category item to view.
    """

    set_redirect_url()

    # Retrieve CategoryItem object for template rendering.
    # If not found, render error template.
    category_item = db_session.query(CategoryItem)\
        .filter_by(id=item_id)\
        .first()
    if not category_item:
        return render_template('error.html',
                               headline_text='Item Not Found',
                               error_text='The specified item was not found.')

    creator = category_item.user
    user = get_user()

    return render_template('category_item_info.html',
                           categories=get_all_objects_of_type(Category),
                           category=category_item.category,
                           item=category_item,
                           items=get_all_items(),
                           creator=creator,
                           user=user)
def catalog_json():
    """
    Function to return JSON of all categories and items.
    """

    categories = get_all_objects_of_type(Category)
    categories_list = []
    for cat in categories:
        categories_list.append(cat.serialize)
        items = db_session.query(CategoryItem).filter_by(category_id=cat.id).all()
        categories_list[-1]['items'] = [item.serialize for item in items]
    return jsonify(categories=categories_list)
def catalog_json():
    """
    Function to return JSON of all categories and items.
    """

    categories = get_all_objects_of_type(Category)
    categories_list = []
    for cat in categories:
        categories_list.append(cat.serialize)
        items = db_session.query(CategoryItem).filter_by(
            category_id=cat.id).all()
        categories_list[-1]['items'] = [item.serialize for item in items]
    return jsonify(categories=categories_list)
def edit_category_item(item_id):
    """
    Function to return a page to edit a category item.

    Args:
        item_id: ID value of the category item to edit.
    """

    user = get_user()
    categories = get_all_objects_of_type(Category)
    edited_item = db_session.query(CategoryItem)\
        .filter_by(id=item_id)\
        .first()
    if not edited_item:
        return render_template('error.html',
                               headline_text='Item Not Found',
                               error_text='The specified item was not found.')

    # Make sure the user is the creator of the item.
    if not user or user and user.id != edited_item.user.id:
        return render_template('error.html',
                               headline_text='Access Denied',
                               error_text='Sorry, but you are not the creator of '\
                               'the item "{}". As such, you are not authorized '\
                               'to make edits to it.'.format(edited_item.name))


    if request.method == 'POST':
        edited_item.name = request.form['name']
        edited_item.description = request.form['description']
        edited_item.category_id = request.form['category']
        db_session.add(edited_item)
        db_session.commit()
        flash('Item Successfully Updated!')
        category = db_session.query(Category)\
            .filter_by(id=edited_item.category_id)\
            .first()
        return redirect(url_for('category_item_info',
                                item_id=edited_item.id))
    else:
        return render_template('edit_category_item.html',
                               item=edited_item,
                               user=user,
                               categories=categories)
def edit_category_item(item_id):
    """
    Function to return a page to edit a category item.

    Args:
        item_id: ID value of the category item to edit.
    """

    user = get_user()
    categories = get_all_objects_of_type(Category)
    edited_item = db_session.query(CategoryItem)\
        .filter_by(id=item_id)\
        .first()
    if not edited_item:
        return render_template('error.html',
                               headline_text='Item Not Found',
                               error_text='The specified item was not found.')

    # Make sure the user is the creator of the item.
    if not user or user and user.id != edited_item.user.id:
        return render_template('error.html',
                               headline_text='Access Denied',
                               error_text='Sorry, but you are not the creator of '\
                               'the item "{}". As such, you are not authorized '\
                               'to make edits to it.'.format(edited_item.name))

    if request.method == 'POST':
        edited_item.name = request.form['name']
        edited_item.description = request.form['description']
        edited_item.category_id = request.form['category']
        db_session.add(edited_item)
        db_session.commit()
        flash('Item Successfully Updated!')
        category = db_session.query(Category)\
            .filter_by(id=edited_item.category_id)\
            .first()
        return redirect(url_for('category_item_info', item_id=edited_item.id))
    else:
        return render_template('edit_category_item.html',
                               item=edited_item,
                               user=user,
                               categories=categories)
def new_category_item():
    """
    Function to return a page to create a new category item.
    """

    set_redirect_url()

    user = get_user()
    categories = get_all_objects_of_type(Category)
    category = None
    if not user:
        return redirect(url_for('login'))
    if request.method == 'POST':
        if request.form.get(
                'name', '') == '' and request.form.get('category', '') != '':
            category = db_session.query(Category)\
                .filter_by(id=request.form.get('category'))\
                .first()
            return render_template('new_category_item.html',
                                   user=user,
                                   category=category,
                                   categories=categories,
                                   request=request)
        new_item = CategoryItem(name=request.form['name'],
                                user_id=login_session['user_id'],
                                description=request.form['description'],
                                category_id=request.form['category'])
        db_session.add(new_item)
        db_session.commit()
        flash('New Item {} Successfully Created!'.format(new_item.name))
        return redirect(url_for('index'))
    else:
        return render_template('new_category_item.html',
                               user=user,
                               category=category,
                               categories=categories)