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 JSON
# ==========================================

with open(JSON_FILE, "r", encoding="utf-8") as f:
    template = json.load(f)

print("SUPPLIER =", template["Supplier"])
print("IMAGE    =", template["ImageFile"])
print("ROTATION =", template["Rotation"])

# ==========================================
# 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
    )

print("IMAGE SIZE =", img.shape)

# ==========================================
# OUTPUT FOLDER
# ==========================================

os.makedirs(
    OUTPUT_DIR,
    exist_ok=True
)

# ==========================================
# CROP SEMUA FIELD
# ==========================================

for field in template["Fields"]:

    nama = field["NamaField"]

    x = int(field["X"])
    y = int(field["Y"])
    w = int(field["Width"])
    h = int(field["Height"])

    crop = img[y:y+h, x:x+w]

    output_file = os.path.join(
        OUTPUT_DIR,
        nama + ".jpg"
    )

    cv2.imwrite(
        output_file,
        crop
    )

    print(
        f"[OK] {nama} -> {output_file}"
    )

print("")
print("SELESAI")