import json

from typing import List, Optional, Dict

import pyscripts

from msgbus import FM_PARAM, TK_SYS_ACK
from bustoken import TK_PROD_GET_COURSES

from actions.models import Course

mb_context = pyscripts.mbcontext
cache_courses = None


def get_courses():
    # type: () -> Optional[List[Course]]

    global cache_courses

    if cache_courses is None:
        try:
            msg = mb_context.MB_EasySendMessage("ProductionSystem", TK_PROD_GET_COURSES, FM_PARAM, None, 10 * 1000000)
            if msg.token == TK_SYS_ACK:
                cache_courses = []
                for course in json.loads(msg.data):
                    cache_courses.append(_create_course(course))
            else:
                return []
        except Exception as _:
            return []

    return cache_courses


def _create_course(course):
    # type: (Dict) -> Course

    course_id = int(course.get("id"))
    course_name = course.get("name")
    course_description = course.get("description")
    course_abbreviation = course.get("abbreviation")
    course_delay = int(course.get("delay"))

    return Course(course_id, course_name, course_description, course_abbreviation, course_delay)
