from __future__ import annotations

from typing import Dict

from mimeparse import parse_mime_type

from clarabot_nano.indexer.extractor.base import StopExtraction
from clarabot_nano.indexer.extractor.xml.base import AbstractCollector, CollectorHandler


class HeadHandler(CollectorHandler):
    TAG = "head"

    def __init__(self, ignored_mimes: set, sub_handlers: Dict[str, AbstractCollector] = None):
        CollectorHandler.__init__(self, sub_handlers)
        self.ignored_mimes = ignored_mimes
        self.meta = dict()
        self.content_type: str = None

    def start(self, tag: str, attrs: dict):
        if tag == "meta":
            if (name := attrs.get("name")) and (content := attrs.get("content")):
                self.meta[name.lower()] = content

    def close(self):
        content_type = self.meta.get("content-type")
        if content_type:
            try:
                t, st, _ = parse_mime_type(content_type)
                self.content_type = f"{t}/{st}"
            except ValueError:
                pass
        if self.content_type and self.content_type in self.ignored_mimes:
            raise StopExtraction("ignored-mimetype")


class TitleHandler(CollectorHandler):
    TAG = "title"

    def __init__(self, sub_handlers: Dict[str, AbstractCollector] = None):
        CollectorHandler.__init__(self, sub_handlers)
        self.title: str = None
        self._texts = []

    def data(self, text: str):
        if text:
            self._texts.append(text)

    def close(self):
        self.title = "".join(self._texts)
        # del self._texts
