#! /usr/bin/env python
# -*- coding: utf-8 -*-
'''
Created on 2023/7/11 11:49:12

@author: LiuKuan
@copyright: Apache License, Version 2.0
'''
from lxml import etree, objectify
from laok.base.fs import file_read_text, file_write_text, path_exist
from laok.base.net.requests_ import req_text
# ===============================================================================
r'''
'''
# ===============================================================================
__all__ = ['load_html', 'load_html_text', 'load_html_url',
           'load_xml', 'load_xml_text',
           'save_xml']
def load_html(filename, base_url=None):
    text = file_read_text(filename)
    return load_html_text(text, base_url=base_url)

def load_html_text(text, base_url=None):
    return etree.HTML(text, base_url=base_url)

def load_html_url(url, cache_file=None, **kws):
    text = None
    base_url = kws.pop('base_url', None)
    if cache_file:
        if path_exist(cache_file):
            text = file_read_text(cache_file)
        else:
            text = req_text(url, **kws)
            file_write_text(cache_file, text)
    else:
        text = req_text(url, **kws)
    return load_html_text(text, base_url)


def load_xml(filename, base_url=None):
    text = file_read_text(filename)
    return load_xml_text(text, base_url=base_url)

def load_xml_text(text, base_url=None):
    return etree.XML(text, base_url=base_url)

def save_xml(filename, data, **kws):
    if isinstance(data, str):
        data = etree.XML(data)

    if isinstance(data, etree._Element):
        data = etree.ElementTree(data)

    if isinstance(data, objectify.ObjectifiedElement):
        data = etree.ElementTree(data)

    if isinstance(data, etree._ElementTree):
        kws.setdefault('encoding', 'utf8')
        # kws.setdefault('strip_text', True)
        kws.setdefault('pretty_print', True)
        data.write(filename, **kws)
        return True
