def search_book():
    title = request.args.get('title', default=None, type=str)

    books = Books.objects(book_title__icontains=title).only(
        'book_title', 'id', 'cover_image', 'avg_rating', 'genres', 'author')

    lim = 10
    total = books.count()
    if total % lim != 0:
        total = int(total / lim) + 1
    else:
        total = int(total / lim)

    if 'user' in session:
        user = Users.objects(username=session['user']).get()
        shelves = []
        for shelf in user['shelves']:
            shelves.append(shelf['shelf_title'])

        return jsonify({
            "books": books.to_json(),
            "total": total,
            "shelves": shelves
        })

    return jsonify({"books": books.to_json(), "total": total})
def get_book_recommendation():
    user = Users.objects(username=session['user']).get()

    genres = []
    ignore_books = []
    for shelf in user.shelves:
        for book in shelf.shelved_books:
            ignore_books.append(book['id'])
            for genre in book.genres:
                genres.append(genre)

    genres = list(dict(Counter(genres).most_common()).keys())

    if len(genres) > 5:
        genres = genres[:5]

    books = Books.objects(
        Q(avg_rating__gte=4.5) & Q(genres__in=list(genres))
        & Q(id__nin=list(set(ignore_books)))).only('book_title', 'id',
                                                   'cover_image', 'author',
                                                   'genres',
                                                   'avg_rating').to_json()

    books = json.loads(books)
    books = random.sample(books, 6)

    return jsonify({"rec": json.dumps(books)})
def remove_review():
    book = request.get_json()['book']

    book = Books.objects(id=book).get()
    book.reviews.remove(book.reviews.get(username=session['user']))
    book.save()

    return jsonify({'result': True})
def add_book_to_shelf():
    shelf = request.get_json()['shelf']
    book = request.get_json()['book']

    user = Users.objects(username=session['user']).get()

    user.shelves.get(shelf_title=shelf).shelved_books.append(
        Books.objects(id=book).get())
    user.save()
    return jsonify({"result": True})
def remove_shelf_book():
    book = request.get_json()['book']
    shelf = request.get_json()['shelf']

    user = Users.objects(username=session['user']).get()
    user.shelves.get(shelf_title=shelf).shelved_books.remove(
        Books.objects(id=book).get())

    user.save()

    return jsonify({'result': True})
def get_book(id):
    try:
        book = Books.objects(id=id).get()
    except:
        return jsonify({"err": "Book not found"})

    if 'user' in session:
        user = Users.objects(username=session['user']).get()
        shelves = []
        for shelf in user['shelves']:
            shelves.append(shelf['shelf_title'])

        return jsonify({"book": book.to_json(), "shelves": shelves})

    return jsonify({"book": book.to_json()})
def add_review():
    review = request.get_json()['review']
    book = request.get_json()['book']

    user = Users.objects(username=session['user']).only(
        'username', 'profile_pic').get()
    book = Books.objects(id=book).get()

    try:
        book.reviews.get(username=session['user'])['review_text'] = review
    except DoesNotExist:
        book.reviews.append(
            Reviews(username=user['username'],
                    profile_pic=user['profile_pic'],
                    review_text=review))

    book.save()

    return jsonify({"result": True})
def rate_book():
    book_id = request.get_json()['book']
    rating = request.get_json()['rating']

    book = Books.objects(id=book_id).get()

    try:
        book.reviews.get(username=session['user'])['rating'] = rating
        book.reviews.get(
            username=session['user'])['created'] = datetime.utcnow()
    except DoesNotExist:
        user = Users.objects(username=session['user']).only(
            'username', 'profile_pic').get()
        book.reviews.append(
            Reviews(username=user['username'],
                    profile_pic=user['profile_pic']))

    book.save()

    return jsonify({"result": True})