def showItem(category, item):
    category = session.query(Category).filter_by(name=category).first()
    # Check if the category exists if user manually enters a url.
    if category is None:
        return categoryAlert()
    item = (
            session.query(Item)
            .filter_by(
                name=item,
                category_id=category.id
            )
            .first()
        )
    # Check if the item exists if user manually enters a url.
    if item is None:
        return itemAlert()
    else:
        i = item.image
        if not i.startswith('http:') and not i.startswith('https:'):
            i = url_for('static', filename=i)
        # Check if user is logged in.
        if 'username' not in login_session:
            return render_template(
                       'itemPublic.html',
                       image=i,
                       category=category,
                       item=item
                   )
        else:
            return render_template(
                      'item.html',
                      image=i,
                      category=category,
                      item=item
                   )
def showItemXML(category, item):
    category = session.query(Category).filter_by(name=category).first()
    # Check if the category exists if user manually enters a url.
    if category is None:
        return categoryAlert()
    item = (
            session.query(Item)
            .filter_by(
                name=item,
                category_id=category.id
            )
            .first()
        )
    if item is None:
        return itemAlert()
    # Transform existing JSON endpoint into XML endpoint.
    # Convert JSON endpoint to a string,
    # then convert the string into a dictionary.
    data = ast.literal_eval(
               showItemJSON(
                   category.name,
                   item.name
               )
               .get_data(as_text=True)
           )
    return app.response_class(
            xmlify(data, wrap="Catalog", indent="  "),
            mimetype="application/xml"
        )
def showCatalogForCategoryJSON(category):
    category = session.query(Category).filter_by(name=category).first()
    # Check if the category exists if user manually enters a url.
    if category is None:
        return categoryAlert()
    items = session.query(Item).filter_by(category_id=category.id).all()
    return jsonify(Items=[i.serialize for i in items])
def showCatalogForCategory(category):
    category = session.query(Category).filter_by(name=category).first()
    # Check if the category exists if user manually enters a url.
    if category is None:
        return categoryAlert()
    else:
        items = session.query(Item).filter_by(category_id=category.id).all()
        count = len(items)
        categories = session.query(Category).all()
        if 'username' not in login_session:
            return render_template(
                       'catalogForCategoryPublic.html',
                       count=count,
                       category=category.name,
                       items=items,
                       categories=categories
                   )
        else:
            return render_template(
                       'catalogForCategory.html',
                       count=count,
                       category=category.name,
                       items=items,
                       categories=categories
                   )
def showCatalogJSON():
    categories = session.query(Category).all()
    items = session.query(Item).all()
    return jsonify(
               Categories=[c.serialize for c in categories],
               Items=[i.serialize for i in items]
           )
def showItemJSON(category, item):
    category = session.query(Category).filter_by(name=category).first()
    # Check if the category exists if user manually enters a url.
    if category is None:
        return categoryAlert()
    item = (
            session.query(Item)
            .filter_by(
                name=item,
                category_id=category.id
            )
            .first()
        )
    if item is None:
        return itemAlert()
    return jsonify(Item=item.serialize)
def showCatalog():
    categories = session.query(Category).all()
    # Query the five latest items.
    items = session.query(Item).order_by(Item.id.desc()).limit(5)
    if 'username' not in login_session:
        return render_template(
                   'catalogPublic.html',
                   categories=categories,
                   items=items
               )
    else:
        return render_template(
                   'catalog.html',
                   categories=categories,
                   items=items
               )
def createUser(login_session):
    newUser = User(name=login_session['username'],
                   email=login_session['email'],
                   picture=login_session['picture'])
    session.add(newUser)
    session.commit()
    user = session.query(User).filter_by(email=login_session['email']).first()
    return user.id
def deleteItemFromCategory(category, item):
    # Do not show the page for deleting an item if the user is not logged in.
    pass
    category = session.query(Category).filter_by(name=category).first()
    if category is None:
        return categoryAlert()
    item = (
            session.query(Item)
            .filter_by(
                name=item,
                category_id=category.id
            )
            .first()
        )
    if item is None:
        return itemAlert()
    else:
        # User can only delete items they have created.
        if item.user_id != login_session['user_id']:
            return modificationAlert()
        # Server received a POST request.
        if request.method == 'POST':
            session.delete(item)
            session.commit()
            flash("%s was deleted!" % item.name.title())
            return (
                    redirect(
                        url_for(
                            'showCatalogForCategory',
                            category=category.name
                        )
                    )
                )
        # Server received a GET request.
        else:
            return render_template(
                       'deleteItem.html',
                       category=category,
                       item=item
                )
def getUserInfo(user_id):
    user = session.query(User).filter_by(id=user_id).first()
    return user
def editItemInCategory(category, item):
    # Do not show the page for editing an item if the user is not logged in.
    pass
    category = session.query(Category).filter_by(name=category).first()
    if category is None:
        return categoryAlert()
    item = (
            session.query(Item)
            .filter_by(
                name=item,
                category_id=category.id
            )
            .first()
        )
    # Check if item exists if user manually enters a url.
    if item is None:
        return itemAlert()
    else:
        # User can only edit items they have created.
        if item.user_id != login_session['user_id']:
            return modificationAlert()
        # Server received POST request.
        if request.method == 'POST':
            newItemName = request.form['name'].strip()
            newItemDescription = request.form['description'].strip()
            if not newItemName or not newItemDescription:
                return blankFieldsAlert()
            # Check for a duplicate with a different item.id
            itemDuplicate = (
                     session.query(Item)
                     .filter_by(
                         name=newItemName.lower(),
                         category_id=category.id
                     )
                     .first()
                )
            # The item being edited can have the same name as the new name,
            # but not another item with a different id.
            # This would create two items with the same name.
            if itemDuplicate is not None and itemDuplicate.id != item.id:
                return duplicateNameAlert()
            # Save the new file upload.
            filename = None
            file = request.files['file']
            if file and allowed_file(file.filename):
                filename = secure_filename(file.filename)
                file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
            # Or grab the url for the image.
            if filename is None:
                filename = request.form['image']
            oldItemName = item.name
            newItemName = request.form['name']
            item.name = newItemName
            item.description = request.form['description']
            item.image = filename
            session.add(item)
            session.commit()
            flash("%s was edited!" % oldItemName.title())
            return (
                    redirect(
                        url_for(
                            'showCatalogForCategory',
                            category=category.name
                        )
                    )
                )
        # Server received GET request.
        else:
            categories = session.query(Category).all()
            return render_template(
                       'editItem.html',
                       categories=categories,
                       category=category,
                       item=item
                )
def getUserID(email):
    try:
        user = session.query(User).filter_by(email=email).first()
        return user.id
    except:
        return None
def createNewItem(category):
    # Do not show the page for creating an item if the user is not logged in.
    pass
    categories = session.query(Category).all()
    category = session.query(Category).filter_by(name=category).first()
    # Check if the category exists if user manually enters a url.
    if category is None:
        return categoryAlert()
    else:
        # Server received POST request.
        if request.method == 'POST':
            newItemName = request.form['name'].strip()
            newItemDescription = request.form['description'].strip()
            # Check if name or description field is blank.
            if not newItemName or not newItemDescription:
                return blankFieldsAlert()
            # Check if an item in the category exists with that name.
            item = (
                    session.query(Item)
                    .filter_by(
                        name=newItemName.lower(),
                        category_id=category.id
                    )
                    .first()
                )
            # Prevent duplicate entries.
            if item is not None:
                return duplicateNameAlert()
            # Save the new file upload.
            filename = None
            file = request.files['file']
            if file and allowed_file(file.filename):
                filename = secure_filename(file.filename)
                file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
            # Or grab the url for the image.
            if filename is None:
                filename = request.form['image']
            item = Item(name=newItemName,
                        description=newItemDescription,
                        category_id=category.id,
                        categoryName=category.name,
                        user_id=login_session['user_id'],
                        image=filename)
            session.add(item)
            session.commit()
            flash("%s was created!" % newItemName.title())
            return (
               redirect(
                    url_for(
                        'showCatalogForCategory',
                        category=category.name
                    )
                )
            )
        else:
            items = session.query(Item).all()
            return render_template(
                    'createNewItem.html',
                    items=items,
                    login_session=login_session,
                    categories=categories,
                    category=category
                )