# ==========================================
# OCR DETAIL TEST
# ==========================================

import json
import os
import cv2

# ==========================================
# KONFIGURASI
# ==========================================

JSON_FILE = r"G:\00. PROJECTS\API\Inventory\templateJSON\indolakto.json"

OUTPUT_DIR = r"G:\00. PROJECTS\API\Inventory\output"

# ==========================================
# LOAD TEMPLATE
# ==========================================

with open(JSON_FILE, "r", encoding="utf-8") as f:

    template = json.load(f)

# ==========================================
# LOAD IMAGE
# ==========================================

image_file = template["ImageFile"]

img = cv2.imread(image_file)

if img is None:

    print("ERROR : Gagal membuka gambar")
    exit()

# ==========================================
# ROTATE
# ==========================================

rotation = int(
    template.get(
        "Rotation",
        0
    )
)

if rotation == 90:

    img = cv2.rotate(
        img,
        cv2.ROTATE_90_CLOCKWISE
    )

elif rotation == 180:

    img = cv2.rotate(
        img,
        cv2.ROTATE_180
    )

elif rotation == 270:

    img = cv2.rotate(
        img,
        cv2.ROTATE_90_COUNTERCLOCKWISE
    )

# ==========================================
# OUTPUT DIR
# ==========================================

os.makedirs(
    OUTPUT_DIR,
    exist_ok=True
)

# ==========================================
# CARI DETAILTABLE
# ==========================================

detail_table = None

for field in template["Fields"]:

    if field["NamaField"] == "DetailTable":

        detail_table = field
        break

if detail_table is None:

    print("ERROR : DetailTable tidak ditemukan")
    exit()

# ==========================================
# INFO DETAILTABLE
# ==========================================

dt_x = int(detail_table["X"])
dt_y = int(detail_table["Y"])
dt_w = int(detail_table["Width"])
dt_h = int(detail_table["Height"])

dt_bottom = dt_y + dt_h

print("")
print("===== DETAIL TABLE =====")
print("X      =", dt_x)
print("Y      =", dt_y)
print("W      =", dt_w)
print("H      =", dt_h)
print("========================")
print("")

# ==========================================
# CROP KOLOM DETAIL
# ==========================================

DETAIL_FIELDS = [
    "NamaBarang",
    "Jumlah",
    "Satuan",
    "HargaBeli",
    "Diskon",
    "PPn",
    "SubTotal",
    "Barcode"
]

for field in template["Fields"]:

    nama = field["NamaField"]

    if nama not in DETAIL_FIELDS:
        continue

    x = int(field["X"])
    y = int(field["Y"])
    w = int(field["Width"])

    # tinggi otomatis sampai bawah DetailTable
    h = dt_bottom - y

    crop = img[
        y:y+h,
        x:x+w
    ]

    output_file = os.path.join(
        OUTPUT_DIR,
        f"{nama}.jpg"
    )

    cv2.imwrite(
        output_file,
        crop
    )

    print(
        f"[OK] {nama:15} -> {output_file}"
    )

print("")
print("SELESAI")