from __future__ import annotations

import sys
from logging import getLogger
from typing import TYPE_CHECKING

from .ast import PanCodeBlock
from .util import EmptyTableError

if TYPE_CHECKING:
    from typing import Optional

    from panflute.elements import CodeBlock, Doc

logger = getLogger('pantable')


def codeblock_to_table(
    options: Optional[dict] = None,
    data: str = '',
    element: Optional[CodeBlock] = None,
    doc: Optional[Doc] = None,
):
    try:
        pan_table_str = (
            PanCodeBlock
            .from_yaml_filter(options=options, data=data, element=element, doc=doc)
            .to_pantablestr()
        )
        if pan_table_str.table_width is not None:
            pan_table_str.auto_width()
        return (
            pan_table_str
            .to_pantable()
            .to_panflute_ast()
        )
    # delete element if table is empty (by returning [])
    # element unchanged if include is invalid (by returning None)
    except FileNotFoundError as e:
        logger.error(f'{e} Codeblock shown as is.')
        return
    except EmptyTableError:
        logger.warning("table is empty. Deleted.")
        # [] means delete the current element
        return []
    except ImportError:
        return

@@ -33,19 +33,8 @@
 ns%0A%0A
-import sys%0A
 from

Update codeblock_to_table.py