import datetime
import hashlib
import json
import time
import traceback


def separate_line(content):
    return "{0} {1} {2}".format("=" * 30, content, "=" * 30)


def pretty_json(obj):
    return json.dumps(obj, indent=2, separators=(',', ': '))


def get_current_time_str():
    return timestamp_to_format_time(get_current_timestamp())


def get_current_timestamp():
    return int(time.time())


def timestamp_to_format_time(timestamp):
    if not timestamp:
        return ""
    try:
        stamp = int(timestamp)
        if stamp > 10000000000:
            stamp = int(stamp / 1000)
        return datetime.datetime.fromtimestamp(stamp).strftime('%Y-%m-%d %H:%M')
    except ValueError:
        traceback.print_exc()
        return ""


def str_in_list_ignore_case(p_str, p_list):
    if not p_str or not p_list:
        return False
    return p_str.lower() in [g.lower() for g in p_list]


def to_int(obj, default=0):
    try:
        return int(obj)
    except BaseException:
        return default


def utc_to_local(utc):
    if not utc:
        return None
    utc_time = datetime.datetime.strptime(utc, "%Y-%m-%dT%H:%M:%SZ")
    localtime = utc_time + datetime.timedelta(hours=8)
    return timestamp_to_format_time(localtime.timestamp())


def md5(raw: str) -> str:
    return hashlib.md5(raw.encode('utf-8')).hexdigest()


def has_intersection(list1, list2, ignore_case=True):
    """
    判断两个list是否有交集， 注意： 当前只能用于str类型的list
    :param list1:
    :param list2:
    :param ignore_case:
    :return:
    """
    if not list1 or not list2:
        return False
    if ignore_case:
        list1 = [g.lower() for g in list1]
        list2 = [g.lower() for g in list2]
    for g1 in list1:
        if g1 in list2:
            return True
    return False


def deep_get(data, key_path, default=None):
    """
    ============ example  ============
    data = {
        "a": {
            "b": [
                {"name": "n1", "age": 8},
                {"name": "n2", "age": 18}
            ],
            "c": {
                "d": "dd"
            }
        }
    }
    =====================================

    :param data:
    :param key_path:
    :param default:
    :return:
    """
    value = data
    try:
        for key in key_path.split('.'):
            if isinstance(value, dict):
                value = value[key]
                continue
            elif isinstance(value, list):
                try:
                    key_parts = key.split(":")
                    if len(key_parts) != 2:
                        value = value[int(key)]
                    else:
                        value = (list(filter(lambda x: x[key_parts[0]] == key_parts[1], value)) or [None])[0]
                    continue
                except BaseException as e:
                    raise KeyError(e)
            else:
                return default
    except KeyError as ke:
        # print("key path is error, return default. ", str(ke))
        return default
    else:
        return value
