# -*- coding: utf-8 -*-
# Copyright (C) 2026 TUD | ZIH
# ralf.klammer@tu-dresden.de

import logging
import os

from .xml import XMLParserBase

log = logging.getLogger(__name__)


class IMEXParser(XMLParserBase):
    def __init__(
        self,
        tree=None,
        path=None,
        filename=None,
        fullpath=None,
        *args,
        **kw,
    ):
        kw["default_ns_prefix"] = "ns"
        if tree is not None:
            super().__init__(tree=tree, *args, **kw)
        elif fullpath:
            super().__init__(fullpath, *args, **kw)
            self.fullpath = fullpath
        elif all([path, filename]):
            self.path = path
            self.filename = filename
            self.fullpath = os.path.join(path, filename)
            super().__init__(os.path.join(path, filename), *args, **kw)
        else:
            raise ValueError("IMEXParser incorrect initialized")

    def __repr__(self):
        return "<IMEXParser: %s>" % self.uri

    def _get_uri(self, object_path):
        # Retrieve the URI basically by looking for the importObject element
        # with the specified local-data attribute
        object = self.find(
            "//importObject[@local-data='%s']" % object_path, get_node=True
        )
        if object is not None:
            return object.attrib.get("textgrid-uri")
        log.error(
            f"Object with local-data='{object_path}' not found in IMEX file"
        )

    def get_uri(self, object_path, crud=None, tg_session_id=None):
        uri = self._get_uri(object_path)
        # If URI has been found
        # and both CRUD interface and session ID are provided,
        # fetch the latest metadata and return the generated textgrid URI
        if uri and crud and tg_session_id:
            md_online = crud.read_metadata(uri, tg_session_id)
            return md_online.object_value.generic.generated.textgrid_uri.value
        # Otherwise, return the retrieved URI as-is
        else:
            return uri
