import ast
import json
from datetime import datetime
from typing import (
    Optional,
    Dict,
)
from xml.etree import cElementTree as eTree


def get_tender_detail(
    tender_line,  # type: eTree.Element
):
    # type: (...) -> Optional[str]

    tender_detail_json = tender_line.get("tenderDetail")
    if not tender_detail_json:
        return None

    try:
        tender_detail = json.loads(tender_detail_json)
    except TypeError:
        return None

    for value in tender_detail.keys():
        if tender_detail[value] is None:
            tender_detail[value] = ""

    return json.dumps(tender_detail)


def get_time_stamp(
    time_stamp,     # type: str
):
    # type: (...) -> Optional[str]

    if time_stamp:
        try:
            ret_time_stamp = datetime.strptime((time_stamp + "Z"), "%Y-%m-%d %H:%M:%SZ")
        except ValueError:
            try:
                ret_time_stamp = datetime.strptime((time_stamp + "Z"), "%Y-%m-%dT%H:%M:%SZ")
            except ValueError:
                return None
        return datetime.strftime(ret_time_stamp, "%Y-%m-%dT%H:%M:%SZ")

    return None


def safe_json_loads(
    text,       # type: str
):
    # type: (...) -> Dict

    try:
        return json.loads(text)
    except json.JSONDecodeError:
        return ast.literal_eval(text)
