from typing import Any, Optional, override
import datetime

from .Schema import Schema
from .__prelude__ import Qt

def _parse_q_date(q_date):
    year, month, day = q_date.getDate()
    return datetime.datetime.strptime(f"{year}-{month}-{day}", "%Y-%m-%d").timestamp()

class DateSchema(Schema):
    class DateNode(Schema.Node):
        def __init__(self, item_model, schema, model, name):
            super().__init__(item_model, schema)
            self.name = name
            self._dialog = None
            self.set_model(model)

        def createEditor(self, parent):
            self._editor = Qt.QCalendarWidget()
            self._editor.activated.connect(lambda q_date: self.requestModelChange.emit(_parse_q_date(q_date)))
            self._dialog = Qt.QDialog(parent)
            self._dialog.setWindowFlags(self._dialog.windowFlags() | Qt.Qt.WindowStaysOnTopHint)
            self._dialog.setWindowTitle(f"Choose a date for : {self.name}")
            layout = Qt.QVBoxLayout()
            layout.addWidget(self._editor)
            self._dialog.setLayout(layout)
            self._dialog.show()
            return self._dialog
        def destroyEditor(self):
            self._dialog.close()
            self._dialog = None
            return True
        def setModelData(self, __editor__):
            return True
        def setEditorData(self, editor):
            return True

        def data(self, role):
            if role == Qt.Qt.ItemDataRole.DisplayRole:
                date_str = datetime.datetime.strftime(datetime.datetime.fromtimestamp(self.model), "%Y-%m-%d")
                return f"{self.name} : {date_str}"
            return None

        def flags(self):
            return Qt.Qt.ItemFlag.ItemIsEditable | super().flags()
        def set_model(self, model):
            super().set_model(model)
            if self._dialog is not None:
                self.destroyEditor()
            self.dataChanged.emit([])

    def __init__(self, name):
        self.name = name

    def make_node(self, item_model, model):
        return self.DateNode(item_model, self, model, self.name)
