# Copyright (c) 2026, UChicago Argonne, LLC
# BSD OPEN SOURCE LICENSE. Full license can be found in LICENSE
# Copyright (c) 2026, UChicago Argonne, LLC
# BSD OPEN SOURCE LICENSE. Full license can be found in LICENSE
# from codeEditor.highlighter.jsonHighlight import JsonHighlighter
import json
import os
from pathlib import Path

import yaml
from qgis.PyQt import QtCore, QtWidgets, uic

from .qjsonmodel import QJsonModel
from .qjsonnode import QJsonNode
from .qjsonview import QJsonView

FORM_CLASS, _ = uic.loadUiType(os.path.join(os.path.dirname(__file__), "forms/jsonEditor.ui"))


# Opening JSON file


class JSONEditor(QtWidgets.QDialog, FORM_CLASS):
    def __init__(self, qgis_project):
        QtWidgets.QDialog.__init__(self)
        self.iface = qgis_project.iface
        self.setupUi(self)
        self._PQgis = qgis_project
        self.project = qgis_project.polaris_project
        self.base_path = self.project.run_config.data_dir

        files = [str(file.name) for file in list(self.base_path.glob("*.json")) + list(self.base_path.glob("*.yaml"))]
        self.cob_list_files.addItems(files)

        self.but_open_external.clicked.connect(self.open_on_editor)
        self.but_save.clicked.connect(self.save_edited)
        self.cob_list_files.currentIndexChanged.connect(self.load_new_file)

        # Json Viewer
        # JsonHighlighter(self.ui_view_edit.document())
        self.ui_tree_view = QJsonView()
        self.ui_tree_view.setStyleSheet('QWidget{font: 10pt "Courier New";}')
        self.ui_grid_layout.addWidget(self.ui_tree_view, 1)

        self.load_new_file()
        self.tabs.currentChanged.connect(self.change_active)

    def load_new_file(self):
        with open(self.base_path / self.cob_list_files.currentText()) as opened_file:
            if "json" in self.cob_list_files.currentText().lower():
                root = QJsonNode.load(json.load(opened_file))
            else:
                root = QJsonNode.load(yaml.safe_load(opened_file))

        self._model = QJsonModel(root, self)

        # proxy model
        self._proxyModel = QtCore.QSortFilterProxyModel(self)
        self._proxyModel.setSourceModel(self._model)
        self._proxyModel.setDynamicSortFilter(False)
        self._proxyModel.setSortRole(QJsonModel.sortRole)
        self._proxyModel.setFilterCaseSensitivity(QtCore.Qt.CaseInsensitive)
        self._proxyModel.setFilterRole(QJsonModel.filterRole)
        self._proxyModel.setFilterKeyColumn(0)

        self.ui_filter_edit.textChanged.connect(self._proxyModel.setFilterRegExp)

        self.ui_tree_view.setModel(self._proxyModel)
        self.ui_tree_view.setColumnWidth(0, 500)

        self.updateBrowser()

    def save_edited(self):
        # We update the data if we have updated it
        if self.tabs.currentIndex() == 0:
            self.updateBrowser()
        text = self.ui_view_edit.toPlainText()
        text_dict = json.loads(text)
        with open(self.base_path / self.cob_list_files.currentText(), "w") as outfile:
            if "json" in self.cob_list_files.currentText().lower():
                outfile.write(text)
            else:
                yaml.dump(text_dict, outfile, default_flow_style=False)

    def open_on_editor(self):
        os.startfile(str(self.base_path / self.cob_list_files.currentText()))

    def change_active(self):
        if self.tabs.currentIndex() == 0:
            self.updateModel()
        else:
            self.updateBrowser()

    def updateModel(self):
        text = self.ui_view_edit.toPlainText()
        root = QJsonNode.load(json.loads(text))

        self._model = QJsonModel(root)
        self._proxyModel.setSourceModel(self._model)

    def updateBrowser(self):
        self.ui_view_edit.clear()
        output = self.ui_tree_view.asDict(None)
        jsonDict = json.dumps(output, indent=4, sort_keys=True)
        self.ui_view_edit.setPlainText(str(jsonDict))

    def closeEvent(self, event):
        event.accept()
