from enum import Enum
from json import dumps, loads
from datetime import datetime

from .. import db
from .database.object_model import Object as DBObject
from .tools import parse_int, parse_text, parse_style


class TicketStatus(Enum):
    ordered = "TicketStatus.ordered"
    ready = "TicketStatus.ready"
    served = "TicketStatus.served"
    canceled = "TicketStatus.canceled"


class Component:
    def __init__(self):
        self.id = -1
        self.parentId = -1
        self.title = ""
        self.quantity = 0
        self.note = ""
        self.style = {}
        self.status = ""
        self.created_dt = 0
        self.updated_dt = 0

    # end def

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

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

        self.id = parse_int(jsonObject.get("id"))
        self.parentId = parse_int(jsonObject.get("parentId"))

        if "designation" in jsonObject:
            self.title = parse_text(jsonObject.get("designation"))
        else:
            self.title = parse_text(jsonObject.get("title"))

        if "qte" in jsonObject:
            self.quantity = parse_int(jsonObject.get("qte"))
        else:
            self.quantity = parse_int(jsonObject.get("quantity"))

        self.note = parse_text(jsonObject.get("note"))
        self.style = parse_text(jsonObject.get("style"))
        self.status = parse_text(jsonObject.get("status"), default=str(TicketStatus.ordered))

    # end def

    def to_json(self):
        """
        TODO: Add definition ... .
        """
        jsonObject = {
            "id": self.id,
            "parentId": self.parentId,
            "title": self.title,
            "quantity": self.quantity,
            "note": self.note,
            "style": self.style,
            "status": self.status,
            "createdDate" : self.created_dt,
            "updatedDate" : self.updated_dt,
        }

        return jsonObject

    # enf def

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

        self.from_json(loads(db_component.obj_json))
        self.id = db_component.obj_object_id
        self.parentId = db_component.obj_parent_id
        self.status = db_component.obj_status
        self.created_dt = datetime.timestamp(db_component.obj_create_dt)
        self.updated_dt = datetime.timestamp(db_component.obj_update_dt)

    # enf def


# end class
