from parser_helper import *


def to_number(txt):

    txt = txt.replace(".", "")
    txt = txt.replace(",", "")
    txt = txt.replace("'", "")
    txt = txt.replace("R", "")

    try:
        return int(txt)
    except:
        return 0


def parse(items):

    result = {
        "supplier": "PT.INDOLAKTO",
        "invoice_no": None,
        "tanggal": None,
        "jatuh_tempo": None,
        "total": None
    }

    # =====================================
    # NOMOR FAKTUR
    # =====================================

    faktur = find_text(
        items,
        "FAKTUR"
    )

    if faktur:

        nomor = find_below(
            items,
            faktur
        )

        if nomor:
            result["invoice_no"] = nomor["text"]

    # =====================================
    # TOTAL
    # =====================================

    total_label = find_contains(
        items,
        "TOTAL YANG DIBAYAR"
    )

    if total_label:

        kandidat = []

        for item in items:

            if item["y"] < total_label["y"]:
                continue

            if item["y"] > total_label["y"] + 250:
                continue

            txt = item["text"]

            if "." in txt or "," in txt:
                kandidat.append(item)

        if kandidat:

            kandidat.sort(
                key=lambda x: to_number(x["text"])
            )

            result["total"] = kandidat[-1]["text"]

    # =====================================
    # DEBUG JATUH TEMPO
    # =====================================

    jatuh_tempo = find_text(
        items,
        "JATUH TEMPO"
    )

    if jatuh_tempo:

        print("\n=== AREA JATUH TEMPO ===\n")

        for item in items:

            dx = abs(
                item["x"] - jatuh_tempo["x"]
            )

            dy = abs(
                item["y"] - jatuh_tempo["y"]
            )

            if dx <= 500 and dy <= 250:

                print(
                    f'({item["x"]},{item["y"]}) '
                    f'{item["text"]}'
                )

        print("\n========================\n")

    return result