import logging
import time

import jwt as pyjwt

from odoo import http
from odoo.http import request

_logger = logging.getLogger(__name__)


class ExamSessionController(http.Controller):

    def _generate_exam_jwt(self, user_id):
        secret = request.env['ir.config_parameter'].sudo().get_param('encoach.jwt_secret')
        if not secret:
            return ''
        return pyjwt.encode(
            {'user_id': user_id, 'exp': int(time.time()) + 7200},
            secret, algorithm='HS256',
        )

    @http.route('/exam/session/<int:attempt_id>', type='http',
                auth='user', website=False)
    def exam_session(self, attempt_id, **kw):
        attempt = request.env['encoach.student.attempt'].sudo().browse(attempt_id)
        if not attempt.exists() or attempt.student_id.id != request.env.user.id:
            return request.not_found()
        token = self._generate_exam_jwt(request.env.user.id)
        return request.render('encoach_exam_session.exam_session_page', {
            'attempt': attempt,
            'session_token': token,
        })

    @http.route('/placement/test/<int:session_id>', type='http',
                auth='user', website=True)
    def placement_test(self, session_id, **kw):
        session = request.env['encoach.cat.session'].sudo().browse(session_id)
        if not session.exists() or session.student_id.id != request.env.user.id:
            return request.not_found()
        return request.render('encoach_exam_session.placement_session_page', {
            'cat_session': session,
        })
