from flask import Blueprint, url_for, jsonify, g
from utils.auth import auth_required
from db.model import db, Badge, UserBadge
from sqlalchemy import select
badge_route = Blueprint('badge', __name__)

@badge_route.route('/listAllBadges')
def all_badges():
    badges: list[Badge] = db.session.execute(select(Badge)).scalars()
    data: list = []
    for bgd in badges:
        data.append({
            'id': bgd.id,
            'name': bgd.name,
            'description': bgd.description,
            'createDate': bgd.createDate,
            'icon': url_for('send_file', filename=bgd.icon),
            'canClaim': bgd.canClaim
        })
    return jsonify({
        'count': len(data),
        'data': data
    })

@badge_route.route('/myBadges')
@auth_required()
def my_badges():
    user_badges: list[UserBadge] = db.session.execute(select(UserBadge).where(
        UserBadge.userID == g.current_user.id
    )).scalars()
    data: list = []
    for ub in user_badges:
        bgd = ub.badge
        data.append({
            'id': ub.id,
            'badgeID': bgd.id,
            'userID': ub.userID,
            'name': bgd.name,
            'description': bgd.description,
            'createDate': bgd.createDate,
            'icon': url_for('send_file', filename=bgd.icon),
            'canClaim': bgd.canClaim,
            'claimedDate': ub.claimedDate,
        })
    return jsonify({
        'count': len(data),
        'data': data
    })