import cv2
import json
import os

# ==========================================
# LOAD JSON
# ==========================================

JSON_FILE = "sukemi3.json"

with open(JSON_FILE, "r", encoding="utf-8") as f:
    tpl = json.load(f)

# ==========================================
# HELPER
# ==========================================

def get_field(name):

    for fld in tpl["Fields"]:
        if fld["NamaField"] == name:
            return fld

    raise Exception(
        f"Field '{name}' tidak ditemukan"
    )

# ==========================================
# LOAD IMAGE
# ==========================================

img = cv2.imread(tpl["ImageFile"])

if img is None:
    raise Exception(
        "Gagal membuka gambar"
    )

# ==========================================
# FIELD
# ==========================================

dt = get_field("DetailTable")

fldNama = get_field("NamaBarang")
fldSub = get_field("SubTotal")

# ==========================================
# RECORD HEIGHT
# ==========================================

record_height = (
    fldSub["Y"] +
    fldSub["Height"]
) - fldNama["Y"]

print()
print("Record Height :", record_height)

# ==========================================
# OFFSET RELATIF
# ==========================================

relNamaX = fldNama["X"] - dt["X"]
relNamaY = fldNama["Y"] - dt["Y"]

relSubX = fldSub["X"] - dt["X"]
relSubY = fldSub["Y"] - dt["Y"]

# ==========================================
# CROP DETAILTABLE
# ==========================================

detail_img = img[
    dt["Y"]:dt["Y"] + dt["Height"],
    dt["X"]:dt["X"] + dt["Width"]
]

# ==========================================
# OUTPUT
# ==========================================

os.makedirs(
    "hasil_stack",
    exist_ok=True
)

# ==========================================
# LOOP RECORD
# ==========================================

row_no = 1

y_record = 0

while True:

    # ==========================
    # Nama Barang
    # ==========================

    nama_x = relNamaX
    nama_y = y_record + relNamaY

    nama_w = fldNama["Width"]
    nama_h = fldNama["Height"]

    # keluar area
    if nama_y + nama_h > detail_img.shape[0]:
        break

    crop_nama = detail_img[
        nama_y:nama_y+nama_h,
        nama_x:nama_x+nama_w
    ]

    # ==========================
    # SubTotal
    # ==========================

    sub_x = relSubX
    sub_y = y_record + relSubY

    sub_w = fldSub["Width"]
    sub_h = fldSub["Height"]

    if sub_y + sub_h > detail_img.shape[0]:
        break

    crop_sub = detail_img[
        sub_y:sub_y+sub_h,
        sub_x:sub_x+sub_w
    ]

    # ==========================
    # SIMPAN
    # ==========================

    cv2.imwrite(
        f"hasil_stack/{row_no:03d}_NamaBarang.jpg",
        crop_nama
    )

    cv2.imwrite(
        f"hasil_stack/{row_no:03d}_SubTotal.jpg",
        crop_sub
    )

    print(
        f"Record {row_no} "
        f"Y={y_record}"
    )

    row_no += 1

    y_record += record_height

print()

print("Nama->Jumlah  :", get_field("Jumlah")["Y"] - fldNama["Y"])
print("Nama->SubTotal:", fldSub["Y"] - fldNama["Y"])
print("RecordHeight  :", record_height)

print("SELESAI")