def get(self):
        """ 
        Returns all of the Shopcarts grouped by user_id 
        This endpoint will give the information of all shopcart of all users
        """

        app.logger.info('Request to list Shopcarts...')

        users = Shopcart.list_users()
        results = ''
        #res = []
        for user_id in users:
            inlist = Shopcart.findByUserId(user_id)
            dt = []
            for item in inlist:
                tmp2 = {
                    "product_id": item.product_id,
                    "price": item.price,
                    "quantity": item.quantity
                }
                dt.append(tmp2)
            tmp = {"user_id": user_id, "products": dt}
            if len(results) > 1:
                results += ","
            results += json.dumps(tmp)
        #res.append()
        #res.append(results)
        res = "[" + results + "]"
        return make_response(res, status.HTTP_200_OK)
    def get(self):
        """
        Get the shopcart list of users
        This endpoint will show the list of the user shopcart list
        with amount more than given amount
        """
        amount = request.args.get('amount')
        app.logger.info(
            "Request to get the list of the user shopcart having more than {}".
            format(amount))

        if amount is None:
            app.logger.info("amount is none")
            abort(status.HTTP_400_BAD_REQUEST, 'parameter amount not found')
        else:
            try:
                app.logger.info("try start")
                amount = float(amount)
                app.logger.info("try end")
            except ValueError:
                app.logger.info("value error")
                abort(status.HTTP_400_BAD_REQUEST,
                      'parameter is not valid: {}'.format(amount))
        users = Shopcart.find_users_by_shopcart_amount(amount)
        app.logger.info("get data")
        return users, status.HTTP_200_OK
    def post(self):
        """
        add a product to a shopcart
        This endpoint will add a new item to a user's shopcart
        """
        app.logger.info('Request to Add an Item to Shopcart')
        check_content_type('application/json')
        shopcart = Shopcart()
        app.logger.info('Payload = %s', api.payload)
        shopcart.deserialize(api.payload)

        q = 0
        try:
            q = int(shopcart.quantity)
        except ValueError:
            app.logger.info("value error")
            #raise DataValidationError
            abort(
                status.HTTP_400_BAD_REQUEST,
                'Quantity parameter is not valid: {}'.format(
                    shopcart.quantity))

        if shopcart.user_id is None or shopcart.user_id == '' or shopcart.product_id is None or shopcart.product_id =='' \
            or shopcart.price is None or shopcart.price == '' or shopcart.quantity is None or shopcart.quantity == '':
            app.logger.info("some parameter is none")
            abort(status.HTTP_400_BAD_REQUEST,
                  'Some data is missing in the request')
        elif q < 1:
            app.logger.info("Added quantity is 0")
            abort(
                status.HTTP_400_BAD_REQUEST,
                'You should input number more than 0 for quantity to add a product'
            )
        else:
            #Check if the entry exists, if yes then increase quantity of product
            exists = Shopcart.find(shopcart.user_id, shopcart.product_id)
            if exists:
                exists.quantity = exists.quantity + q
                exists.save()
                shopcart = exists

            shopcart.save()

            app.logger.info(
                'Item with new id [%s] saved to shopcart of user [%s]!',
                shopcart.user_id, shopcart.product_id)
            location_url = api.url_for(ProductResource,
                                       user_id=shopcart.user_id,
                                       product_id=shopcart.product_id,
                                       _external=True)
            return shopcart.serialize(), status.HTTP_201_CREATED, {
                'Location': location_url
            }
    def delete(self, user_id, product_id):
        """
        Delete a product from a user's shopcart

        This endpoint will delete a product based the id of product and user specified in the path
        """
        app.logger.info(
            'Request to Delete a product with id [%s] from user with id [%s]',
            user_id, product_id)
        shopcart = Shopcart.find(user_id, product_id)
        if shopcart:
            shopcart.delete()
        return '', status.HTTP_204_NO_CONTENT
    def delete(self, user_id):
        """
       Delete Product of User
       This endpoint will delete all Product of user based the user_id specified in the path
       """

        app.logger.info('Request to delete a shopcart of user id [%s]',
                        user_id)
        shopcarts = Shopcart.findByUserId(user_id)
        if shopcarts:
            for shopcart in shopcarts:
                shopcart.delete()
        return '', status.HTTP_204_NO_CONTENT
    def get(self, user_id, product_id):
        """
        Retrieve a product from user's shopcart

        This endpoint will return a product having given product_id from user having given user_id
        """
        app.logger.info(
            "Request to Retrieve a product with id [%s] from shopcart of user with id [%s]",
            product_id, user_id)
        result = Shopcart.find(user_id, product_id)
        if not result:
            raise NotFound(
                "User with id '{uid}' doesn't have product with id '{pid}' was not found.' in the shopcart "
                .format(uid=user_id, pid=product_id))
        return result.serialize(), status.HTTP_200_OK
 def get(self, user_id):
     """ Get the shopcart entry for user (user_id)
    This endpoint will show the list of products in user's shopcart from the database
    """
     app.logger.info(
         "Request to get the list of the product in a user [%s]'s shopcart",
         user_id)
     shopcarts = []
     shopcarts = Shopcart.findByUserId(user_id)
     print(shopcarts.count())
     #if not shopcarts:
     #api.abort(status.HTTP_404_NOT_FOUND, "Shopcart with user_id '{}' was not found.".format(user_id))
     if shopcarts.count() == 0:
         api.abort(
             status.HTTP_404_NOT_FOUND,
             "Shopcart with user_id '{}' was not found.".format(user_id))
         #raise NotFound("Shopcart with user_id '{}' was not found.".format(user_id))
     results = [shopcart.serialize() for shopcart in shopcarts]
     return results, status.HTTP_200_OK
    def get(self, user_id):
        """ Get the shopcart entry for user (user_id)
       This endpoint will show the total amount of the all items in the shopcart along with the list of items in user's shopcart 
       """

        app.logger.info(
            "Request to get the total amount of a user [%s]'s shopcart",
            user_id)
        total_amount = 0.0
        shopcarts = Shopcart.findByUserId(user_id)
        for shopcart in shopcarts:
            total_amount = total_amount + (shopcart.price * shopcart.quantity)
        total_amount = round(total_amount, 2)

        inlist = [shopcart.serialize() for shopcart in shopcarts]

        dt = {'products': inlist, 'total_price': total_amount}

        results = json.dumps(dt)
        return make_response(results, status.HTTP_200_OK)
    def put(self, user_id, product_id):
        """
        Update a Shopcart entry specific to that user_id and product_id
        This endpoint will update a Shopcart based the data in the body that is posted
        """
        app.logger.info(
            'Request to Update a product with id [%s] from user with id [%s]',
            user_id, product_id)
        check_content_type('application/json')
        shopcart = Shopcart.find(user_id, product_id)
        if not shopcart:
            raise NotFound(
                "User with id '{uid}' doesn't have product with id '{pid}' was not found.' in the shopcart "
                .format(uid=user_id, pid=product_id))

        data = api.payload
        app.logger.info(data)
        shopcart.deserialize(data)
        q = 0
        try:
            q = int(shopcart.quantity)
        except ValueError:
            app.logger.info("value error")
            abort(
                status.HTTP_400_BAD_REQUEST,
                'Quantity parameter is not valid: {}'.format(
                    shopcart.quantity))

        if q < 1:
            app.logger.info("Added quantity is 0")
            abort(
                status.HTTP_400_BAD_REQUEST,
                'You should input number more than 0 for quantity to add a product'
            )

        shopcart.user_id = user_id
        shopcart.product_id = product_id
        shopcart.save()
        return shopcart.serialize(), status.HTTP_200_OK
def init_db():
    """ Initlaize the SQLAlchemy app"""
    Shopcart.init_db()
def shopcarts_reset():
    """ Clears all items from shopcarts for all users from the database 
    This endpoint will remove all the shopcart information in the server
    """
    Shopcart.remove_all()
    return '', status.HTTP_204_NO_CONTENT