# ==========================================
# SPLIT ALL COLUMNS
# ==========================================

import cv2
import os

OUTPUT_DIR = r"G:\00. PROJECTS\API\Inventory\output"
ROWS_DIR = r"G:\00. PROJECTS\API\Inventory\output\rows"

os.makedirs(
    ROWS_DIR,
    exist_ok=True
)

# ==========================================
# DETECT ROWS FROM NAMABARANG
# ==========================================

master_file = os.path.join(
    OUTPUT_DIR,
    "NamaBarang.jpg"
)

img = cv2.imread(master_file)

if img is None:

    print("ERROR : NamaBarang.jpg tidak ditemukan")
    exit()

gray = cv2.cvtColor(
    img,
    cv2.COLOR_BGR2GRAY
)

_, thresh = cv2.threshold(
    gray,
    0,
    255,
    cv2.THRESH_BINARY_INV + cv2.THRESH_OTSU
)

height, width = thresh.shape

rows = []

for y in range(height):

    count = cv2.countNonZero(
        thresh[y:y+1, :]
    )

    rows.append(count)

inside = False
start_y = 0

row_ranges = []

for y, value in enumerate(rows):

    if value > 5 and not inside:

        start_y = y
        inside = True

    elif value <= 5 and inside:

        end_y = y

        if end_y - start_y > 5:

            row_ranges.append(
                (start_y, end_y)
            )

        inside = False

# skip header
if len(row_ranges) > 0:

    row_ranges = row_ranges[1:]

print("")
print("===== ROW RANGES =====")

for i, (y1, y2) in enumerate(
    row_ranges,
    start=1
):

    print(
        f"{i:03d} : {y1}-{y2}"
    )

print("")

# ==========================================
# DETAIL COLUMNS
# ==========================================

DETAIL_COLUMNS = [

    "NamaBarang",
    "Jumlah",
    "Satuan",
    "HargaBeli",
    "Diskon",
    "PPn",
    "SubTotal",
    "Barcode"

]

# ==========================================
# SPLIT ALL
# ==========================================

for col_name in DETAIL_COLUMNS:

    file_name = os.path.join(
        OUTPUT_DIR,
        f"{col_name}.jpg"
    )

    img = cv2.imread(file_name)

    if img is None:

        print(
            f"SKIP : {col_name}"
        )

        continue

    h, w = img.shape[:2]

    for row_no, (y1, y2) in enumerate(
        row_ranges,
        start=1
    ):

        margin = 3

        top = max(
            0,
            y1 - margin
        )

        bottom = min(
            h,
            y2 + margin
        )

        row_img = img[
            top:bottom,
            :
        ]

        out_file = os.path.join(
            ROWS_DIR,
            f"{col_name}_{row_no:03d}.jpg"
        )

        cv2.imwrite(
            out_file,
            row_img
        )

print("")
print("SELESAI")