from django.http.response import JsonResponse

from BookStore import error
from BookStore.function import check_login, check_method, get_post_json, get_username_by_token

from user.models import User
from store.models import Store, Book
from cart.models import Cart


# Create your views here.
@check_login
@check_method('GET')
def cart_num_view(request):
    username = get_username_by_token(request)

    try:
        user = User.objects.get(username=username)
        books = Cart.objects.filter(user=user)
        return JsonResponse({
            'message': 'ok',
            'num': len(books),
        })

    # 用户ID不存在
    except User.DoesNotExist:
        code, message = error.user_id_doesnt_exist(username)
        return JsonResponse({
            'message': message,
        }, status=code)

    # 其他数据库错误
    except Exception as e:
        print(e)
        code, message = error.database_error()
        return JsonResponse({
            'message': message,
        }, status=code)


@check_login
@check_method('GET')
def my_cart_view(request):
    username = get_username_by_token(request)

    try:
        user = User.objects.get(username=username)
        books = Cart.objects.filter(user=user).order_by('-updateTime')

        stores_temp = []
        stores = []
        for book in books:
            store_id = book.store.storeName

            if store_id not in stores_temp:
                stores_temp.append(store_id)
                stores.append({
                    'store_id': store_id,
                    'book_num': 1,
                    'books': [book.info_json()],
                })
            else:
                index = stores_temp.index(store_id)
                stores[index]['book_num'] += 1
                stores[index]['books'].append(book.info_json())

        return JsonResponse({
            'message': 'ok',
            'store_num': len(stores),
            'stores': stores
        })

    # 用户名不存在
    except User.DoesNotExist:
        code, message = error.user_id_doesnt_exist(username)
        return JsonResponse({
            'message': message,
        }, status=code)

    # 其他数据库错误
    except Exception as e:
        print(e)
        code, message = error.database_error()
        return JsonResponse({
            'message': message,
        }, status=code)


@check_login
@check_method('POST')
def add_view(request):
    username = get_username_by_token(request)

    post = get_post_json(request)
    store_id = post.get('store_id')
    book_id = post.get('book_id')
    count = int(post.get('count'))

    if store_id is None or book_id is None or count is None \
            or type(count) != int:
        code, message = error.invalid_parameter()
        return JsonResponse({
            'message': message,
        }, status=code)

    try:
        user = User.objects.get(username=username)
        store = Store.objects.get(storeName=store_id)
        book = Book.objects.get(bookID=book_id)

        try:
            cart = Cart.objects.get(user=user, store=store, book=book)
            cart.count += count
            cart.save()

            return JsonResponse({
                'message': 'ok'
            })

        except Cart.DoesNotExist:
            try:
                Cart.objects.create(user=user, store=store, book=book, count=count)
                return JsonResponse({
                    'message': 'ok'
                })

            except Exception as e2:
                print('Create(Insert) error!', e2)
                code, message = error.database_error()
                return JsonResponse({
                    'message': message,
                }, status=code)

        except Exception as e3:
            print('Update error!', e3)
            code, message = error.database_error()
            return JsonResponse({
                'message': message,
            }, status=code)

    # 用户名不存在
    except User.DoesNotExist:
        code, message = error.user_id_doesnt_exist(username)
        return JsonResponse({
            'message': message,
        }, status=code)

    except Store.DoesNotExist:
        code, message = error.store_id_doesnt_exist(store_id)
        return JsonResponse({
            'message': message,
        }, status=code)

    except Book.DoesNotExist:
        code, message = error.book_id_doesnt_exist(book_id)
        return JsonResponse({
            'message': message,
        }, status=code)

    # 其他数据库错误
    except Exception as e:
        print(e)
        code, message = error.database_error()
        return JsonResponse({
            'message': message,
        }, status=code)


@check_login
@check_method('POST')
def delete_view(request):
    username = get_username_by_token(request)

    post = get_post_json(request)
    user_id = post.get('user_id')
    stores = post.get('stores')

    if username != user_id:
        code, message = error.authorization_fail()
        return JsonResponse({
            'message': message,
        }, status=code)

    if user_id is None or stores is None:
        code, message = error.invalid_parameter()
        return JsonResponse({
            'message': message,
        }, status=code)

    temp_store_id = None
    temp_book_id = None

    try:
        user = User.objects.get(username=user_id)

        for store_ in stores:
            store_name = store_['store_id']
            temp_store_id = store_name
            store = Store.objects.get(storeName=store_name)
            for bookID in store_['books']:
                temp_book_id = bookID
                book = Book.objects.get(bookID=bookID)
                Cart.objects.get(user=user, store=store, book=book).delete()

                return JsonResponse({
                    'message': 'ok',
                })

    except Store.DoesNotExist:
        code, message = error.store_id_doesnt_exist(temp_store_id)
        return JsonResponse({
            'message': message,
        }, status=code)

    except Book.DoesNotExist:
        code, message = error.book_id_doesnt_exist(temp_book_id)
        return JsonResponse({
            'message': str(message),
        }, status=code)

    except User.DoesNotExist:
        code, message = error.user_id_doesnt_exist(user_id)
        return JsonResponse({
            'message': message,
        }, status=code)

    except Exception as e:
        print(e)
        code, message = error.database_error()
        return JsonResponse({
            'message': message,
        }, status=code)