from tinydb import TinyDB, Query
from datetime import datetime
from pprint import pprint
# 데이터베이스 생성 및 연결
db = TinyDB('userdb.json')
###########################################
# 데이터베이스 쿼리 함수들                 #
###########################################

# 데이터가 없으면 샘플 데이터 추가
def create_table():
    if len(db.all()) == 0:    
        users = [
            {'id': 1, 'name': '전 John', 'email': 'john@gmail.com', 'age': 20, 'created_at': '2021-01-01 00:00:00'},
            {'id': 2, 'name': '오 Jane', 'email': 'jane@gmail.com', 'age': 25, 'created_at': '2021-01-02 00:00:00'},
            {'id': 3, 'name': '방 Bob', 'email': 'bob@gmail.com', 'age': 30, 'created_at': '2021-01-03 00:00:00'},
            {'id': 4, 'name': '윤 Alice', 'email': 'alice@gmail.com', 'age': 35, 'created_at': '2021-01-04 00:00:00'},
            {'id': 5, 'name': '김 Bill', 'email': 'bill@gmail.com', 'age': 40, 'created_at': '2021-01-05 00:00:00'},
        ]
        db.insert_multiple(users)

def get_new_id():
    users = fetch_users()
    new_id = users[-1]['id'] + 1
    return new_id

def fetch_users():
    return db.all()

def fetch_user_by_id(id):
    users = db.search(Query().id == id)
    if len(users) == 0:
        return []
    else:
        return users.pop()

def fetch_user_by_email(email):
    users = db.search(Query().email == email)
    if len(users) == 0:
        return []
    else:
        return users.pop()

def insert_user(user):
    # new_user = user_from_input()
    db.insert(user)

def update_user(user):
    db.update(user, Query().id == user['id'])

def delete_user(id):
    db.remove(Query().id == id)


