from flask import Blueprint, abort, request
from orm.attend import Attend
from datetime import datetime
from uuid import UUID
import json

bp = Blueprint('attendance', __name__)


@bp.route('/On/<uid>', methods=['POST'])
def append(uid):
    if uid is None:
        return 'Error'
    try:
        uid_user = Attend.select().where((Attend.uid == UUID(uid)) & (Attend.date == datetime.today())).order_by(Attend.on_date)
        if len(uid_user) == 0:
            attend = Attend.create(uid=uid, date=datetime.now(), on_date=datetime.now().timestamp())
            return str(attend.on_date)
        else:
            return 'Exist'
    except Exception:
        attend = Attend.create(uid=uid, date=datetime.now(), on_date=datetime.now().timestamp())
        return str(attend.on_date)


@bp.route('/Off/<uid>', methods=['POST'])
def off_append(uid):
    if uid is None:
        return 'Error'
    try:
        uid_user = Attend.select().where((Attend.uid == UUID(uid)) & (Attend.date == datetime.today())).order_by(Attend.on_date)
        print(len(uid_user))
        if len(uid_user) == 0:
            return 'Error'
        else:
            if len(uid_user) == 1:
                attend = uid_user[0]
                attend.off_date = datetime.now().timestamp()
                off = attend.off_date
                on = attend.on_date.timestamp()
                if off - on > 3600 * 8:
                    attend.is_fine = True
                return str(attend.off_date)
            return 'Error'
    except Exception:
        print('Exception')
        return 'Error'


@bp.route('/QUERY/<uid>', methods=['POST'])
def query(uid):
    if uid is None:
        return 'Error'
    try:
        uid_user = Attend.select().where((Attend.uid == UUID(uid))).order_by(Attend.on_date)
        print(len(uid_user))
        if len(uid_user) == 0:
            return 'Null'
        else:
            lst = []
            for record in uid_user:
                dic_record = {'on_date': record.on_date.timestamp(), 'off_date': record.off_date.timestamp(), 'date': str(record.date), 'is_fine': record.is_fine}
                lst.append(dic_record)
            if len(lst) == 0:
                return 'Error'
            else:
                print(lst)
                return json.dumps(lst)
    except Exception:
        print('Exception')
        return 'Error'
