# -*- coding: utf-8 -*-
import mammoth
import markdown
from ddans.native.hook import NHook
from ddans.native.system import NSystem


class FConvert():
    @staticmethod
    def read_md_from_doc(file: str, default=None):
        try:
            if not NHook.isvalid_str(file):
                return default
            filepath = NSystem.get_full_path(file)
            if not NSystem.exists(filepath):
                return default
            result = mammoth.convert_to_markdown(filepath)
            return result.value
        except Exception:
            return default

    @staticmethod
    def read_html_from_doc(file: str, default=None):
        try:
            if not NHook.isvalid_str(file):
                return default
            filepath = NSystem.get_full_path(file)
            if not NSystem.exists(filepath):
                return default
            md = mammoth.convert_to_markdown(filepath)
            return FConvert.markdown_to_html(md.value, default)
        except Exception:
            return default

    @staticmethod
    def read_html_from_md(file: str, default=None):
        try:
            if not NHook.isvalid_str(file):
                return default
            filepath = NSystem.get_full_path(file)
            if not NSystem.exists(filepath):
                return default
            text = NSystem.read_data(filepath)
            return markdown.markdown(NHook.buffer_utf8(text))
        except Exception:
            return default

    @staticmethod
    def markdown_to_html(content: str, default=None):
        try:
            if not NHook.isvalid_str(content):
                return default
            return markdown.markdown(content)
        except Exception:
            return default
