import datetime

from typing import Any

from flask.json import JSONEncoder as Base

from pycs.database.util.JSONEncoder import JSONEncoder as DatabaseEncoder
from pycs.jobs.util.JSONEncoder import JSONEncoder as JobsEncoder


class JSONEncoder(Base):
    """
    prepares job and DB objects to be json encoded
    """

    def default(self, o: Any) -> Any:
        module = o.__class__.__module__

        if module.startswith('pycs.database'):
            return DatabaseEncoder().default(o)

        if module.startswith('pycs.jobs'):
            return JobsEncoder().default(o)

        if isinstance(o, datetime.datetime):
            return str(o)

        if isinstance(o, dict):
            return o

        return o.__dict__
