from json import dumps, loads
from datetime import datetime

from .. import db
from .database.object_model import Object as DBObject
from .component_model import Component


class Item(Component):
    def __init__(self):
        super().__init__()
        self.components = []

    # end def

    def from_json(self, jsonObject):
        """
        Extracts the attributes of the jsonObject.

        Example of the expected json :
        {
            "designation": "Formule XXXXXXX",
            "qte": 2,
            "note": "Sans quelque chose",
            "style": {},
            "formule": [
                {
                    "designation": "Plat XXXXXXX",
                    "qte": 1,
                    "note": "Sans quelque chose",
                    "style": {}
                },
                {
                    "designation": "Plat XXXXXXX",
                    "qte": 1,
                    "note": "Sans quelque chose",
                    "style": {}
                }
            ]
        }
        """

        super().from_json(jsonObject)

        if "formule" in jsonObject:
            if isinstance(jsonObject.get("formule"), list):
                for jsonItem in jsonObject.get("formule"):
                    component = Component()
                    component.from_json(jsonItem)
                    self.components.append(component)
                # end for
            # end if
        # end if

    # end def

    def to_json(self):
        """
        TODO: Add definition ... .
        """

        jsonObject = super().to_json()
        jsonObject["components"] = []

        for component in self.components:
            jsonObject["components"].append(component.to_json())

        return jsonObject

    # enf def

    def from_db(self, db_item: DBObject):
        """
        TODO: Add definition ... .
        """

        self.from_json(loads(db_item.obj_json))

        db_components = (
            db.session.query(DBObject)
            .filter(DBObject.obj_parent_id == db_item.obj_object_id)
            .all()
        )

        for db_component in db_components:
            component = Component()
            component.from_db(db_component)
            self.components.append(component)
        
        self.id = db_item.obj_object_id
        self.parentId = db_item.obj_parent_id
        self.status = db_item.obj_status
        self.created_dt = datetime.timestamp(db_item.obj_create_dt)
        self.updated_dt = datetime.timestamp(db_item.obj_update_dt)

    # enf def


# end class
