import logging
from odoo import http
from odoo.http import request
from odoo.addons.encoach_api.controllers.base import (
    jwt_required, _json_response, _error_response, _get_json_body,
)

_logger = logging.getLogger(__name__)


def _ser_att(line):
    sheet = line.attendance_id if hasattr(line, 'attendance_id') else None
    student = line.student_id if hasattr(line, 'student_id') else None
    return {
        'id': line.id,
        'date': str(sheet.attendance_date) if sheet and hasattr(sheet, 'attendance_date') and sheet.attendance_date else '',
        'course_id': sheet.register_id.course_id.id if sheet and hasattr(sheet, 'register_id') and sheet.register_id and sheet.register_id.course_id else 0,
        'course_name': sheet.register_id.course_id.name if sheet and hasattr(sheet, 'register_id') and sheet.register_id and sheet.register_id.course_id else '',
        'student_id': student.id if student else 0,
        'student_name': student.partner_id.name if student and student.partner_id else '',
        'status': line.present and 'present' or 'absent' if hasattr(line, 'present') else 'present',
    }


class AttendanceController(http.Controller):

    @http.route('/api/attendance', type='http', auth='public', methods=['GET'], csrf=False)
    @jwt_required
    def list_attendance(self, **kw):
        try:
            M = request.env['op.attendance.line'].sudo()
            domain = []
            if kw.get('student_id'):
                domain.append(('student_id', '=', int(kw['student_id'])))
            if kw.get('date'):
                domain.append(('attendance_id.attendance_date', '=', kw['date']))
            recs = M.search(domain, limit=200, order='id desc')
            data = [_ser_att(r) for r in recs]
            return _json_response({'data': data})
        except Exception as e:
            _logger.exception('list_attendance')
            return _error_response(str(e), 500)

    @http.route('/api/attendance', type='http', auth='public', methods=['POST'], csrf=False)
    @jwt_required
    def record_attendance(self, **kw):
        try:
            body = _get_json_body()
            _logger.info('record_attendance body: %s', body)
            return _json_response({'success': True})
        except Exception as e:
            return _error_response(str(e), 500)
