def item(item_id):
    try:
        # Fetch the data from database
        item = act.item(id=item_id)
        return render_template("item.html", item=item)

    except BaseException:
        return redirect(url_for("notFound"))
def deleteItem(item_id):
    try:
        # Fetch the data from database
        item = act.item(id=item_id)

        # Check the authority of the logged-in user
        if item.user_id == g.USER.id:
            if request.method == "GET":
                TYPE = "item"
                return render_template("delete.html", TYPE=TYPE, object=item)

            elif request.method == "POST":

                # Check if image is already exist
                # and remove it
                if item.image:
                    try:
                        os.remove(
                            os.path.join(__root_directory__, item.image[1:]))
                    except BaseException:
                        pass

                # Make delete action on database and check if passed correctly
                if act.delete_item(item=item):

                    flash(
                        Markup("The item has been deleted successfully. "
                               'Go to your <a href="/me">profile</a>.'))

                else:

                    flash(Markup("An error occurred during deletion."))

                # Check if the next redirect is not related to the deleted item
                # and redirect to the user profile
                if (request.args.get("next", "") == url_for(
                        "item", item_id=item_id) or request.args.get(
                            "next", "") == url_for("editItem", item_id=item_id)
                        or request.args.get("next", "") == url_for(
                            "deleteItem", item_id=item_id)):
                    return redirect(url_for("me"))

                return redirect(request.args.get("next", ""))

    except BaseException:
        pass

    return redirect(url_for("notFound"))
def api_v1_items():
    item_id = request.args.get("id", "")
    view_type = request.args.get("view", "")
    if view_type == "full":
        view_properity = "serialize"
    else:
        view_properity = "mini_serialize"

    if item_id:
        try:
            item = act.item(id=item_id)
            return jsonify(getattr(item, view_properity))

        except BaseException:
            return jsonify(error="NOT FOUND"), 404
    else:
        item_owner = request.args.get("for", "all")
        if item_owner == "all":
            return jsonify(all_items=[
                getattr(item, view_properity) for item in act.all_items()
            ])

        elif item_owner == "me":
            return jsonify(my_items=[
                getattr(item, view_properity)
                for item in act.items(For="user", pointer=g.USER.id)
            ])

        else:
            try:
                items = act.items(For="user", pointer=item_owner)
                return jsonify(user_items=[
                    getattr(item, view_properity) for item in items
                ])

            except BaseException:
                return jsonify(error="NOT FOUND"), 404
def api_v1_item():
    item_id = request.args.get("id", "")
    category_id = request.form.get("category", "")

    if request.method == "POST":
        if not act.category(id=category_id):
            return jsonify(error="Category ID is incorrect"), 404

        if act.add_item(
                user_id=g.USER.id,
                category_id=category_id,
                name=request.form.get("name", ""),
                description=request.form.get("description", ""),
                image=request.form.get("image", ""),
        ):

            return jsonify("The item has been added successfully")

        else:

            return jsonify(error="An error occurred adding the item"), 404

    else:
        try:
            item = act.item(id=item_id)
            if request.method == "PUT":
                if not act.category(id=category_id):
                    return jsonify(error="Category ID is incorrect"), 404

                if item.user_id == g.USER.id:

                    if item.image:
                        try:
                            os.remove(
                                os.path.join(__root_directory__,
                                             item.image[1:]))
                        except BaseException:
                            pass

                    if act.edit_item(
                            item=item,
                            category_id=category_id,
                            name=request.form.get("name", ""),
                            description=request.form.get("description", ""),
                            image=request.form.get("image", ""),
                    ):

                        return jsonify("The item has been edited successfully")

                    else:

                        return (
                            jsonify(
                                error="An error occurred editing the item"),
                            404,
                        )

                else:

                    return (
                        jsonify(
                            error="You are not allowed to modify this item"),
                        404,
                    )

            elif request.method == "DELETE":

                if item.user_id == g.USER.id:

                    if item.image:
                        try:
                            os.remove(
                                os.path.join(__root_directory__,
                                             item.image[1:]))
                        except BaseException:
                            pass

                    if act.delete_item(item=item):

                        return jsonify(
                            "The item has been deleted successfully")

                    else:

                        return (
                            jsonify(
                                error="An error occurred deleting the item"),
                            404,
                        )

                else:

                    return (
                        jsonify(
                            error="You are not allowed to delete this item"),
                        404,
                    )

        except BaseException:
            return jsonify(error="NOT FOUND"), 404
def editItem(item_id):
    try:
        # Fetch the data from database
        item = act.item(id=item_id)

        # Check the authority of the logged-in user
        if item.user_id == g.USER.id:
            if request.method == "GET":
                return render_template(
                    "edit_item.html",
                    item=item,
                    your_categories=act.categories(user_id=g.USER.id),
                    others_categories=act.all_categories(),
                )

            elif request.method == "POST":
                allowed_image_extension = {"png", "jpg", "jpeg", "gif"}
                item_image = request.files["image"]
                item_image_name = [""]

                # Check if image is in a correct formats and extensions
                if item_image and allowed_file(item_image.filename,
                                               allowed_image_extension):

                    # Check if image is already exist
                    # and remove it to replace it with the new one
                    if item.image:
                        try:
                            os.remove(
                                os.path.join(__root_directory__,
                                             item.image[1:]))
                        except BaseException:
                            pass

                    item_image_extension = item_image.filename.split(".")[-1]
                    item_image_name[0] = random_filename(item_image_extension)

                    image_exist = True

                    # Generate a random name for image safely
                    while image_exist:
                        try:
                            image = open(
                                os.path.join(
                                    __root_directory__ + "/resources/image",
                                    item_image_name[0]),
                                "r",
                            )
                            image.close()
                            item_image_name[0] = random_filename(
                                item_image_extension)
                        except BaseException:
                            image_exist = False

                    # Save the new image
                    item_image.save(
                        os.path.join(__root_directory__ + "/resources/image",
                                     item_image_name[0]))

                # Make edit action on database and check if passed correctly
                if act.edit_item(
                        item=item,
                        name=request.form.get("name", ""),
                        description=request.form.get("description", ""),
                        image=(url_for(
                            "resources",
                            filename="image/%s" % item_image_name[0],
                        ) if act.not_empty(item_image_name[0]) else ""),
                        category_id=request.form.get("category", ""),
                ):

                    flash(
                        Markup("""The item has been edited successfully. \
                            Go to your <a href="/me">profile</a>."""))

                else:

                    flash(Markup("An error occurred editing your item."))

                return redirect(request.args.get("next", ""))

    except BaseException:
        pass

    return redirect(url_for("notFound"))