import json

from task_selector.task import Task
from task_selector.taskexceptions import JSONMissingFieldsExepction


class TaskAdapter:
    """Adapter which takes json input or simile json input with single quotes and
     generates a list of Tasks"""


    def get_tasks_from_json(self, json_str: str):
        """Return list of Task from json string"""
        json_tasks = json.loads(json_str.replace("'", '"'))
        try:
            return [Task(json_task["name"], json_task["resources"], json_task["profit"])
                for json_task in json_tasks]
        # Create exception if some mandatory field missing
        except(KeyError) as exc:
            raise JSONMissingFieldsExepction(exc)


    def get_json_from_tasks(self, tasks: list[Task]):
        """Return json like string from list[Task]"""
        return json.dumps([t.__dict__ for t in tasks]).replace('"', "'")


