# ==========================================
# OCR TEMPLATE TEST
# ==========================================

import json
import os
import cv2

from paddleocr import PaddleOCR
from parser_header import normalize_text

# ==========================================
# 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("")
print("===== TEMPLATE =====")
print("SUPPLIER =", template["Supplier"])
print("IMAGE    =", template["ImageFile"])
print("ROTATION =", template["Rotation"])
print("====================")
print("")

# ==========================================
# 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
)

# ==========================================
# SIMPAN HASIL ROTASI
# ==========================================

rotated_file = os.path.join(
    OUTPUT_DIR,
    "rotated.jpg"
)

cv2.imwrite(
    rotated_file,
    img
)

print("")
print("ROTATED =", rotated_file)
print("")

# ==========================================
# INIT OCR
# ==========================================

print("Loading PaddleOCR ...")

ocr = PaddleOCR(
    use_angle_cls=True,
    lang="en"
)

print("PaddleOCR Ready")
print("")

# ==========================================
# OCR RESULT
# ==========================================

ocr_result = {}

# ==========================================
# LOOP FIELD
# ==========================================

print("===== OCR HEADER =====")
print("")

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
    )

    try:

        result = ocr.ocr(
            output_file,
            cls=True
        )

        text = ""

        if result and result[0]:

            texts = []

            for line in result[0]:

                texts.append(
                    line[1][0]
                )

            text = " ".join(texts)

        text = normalize_text(
            nama,
            text
        )

        ocr_result[nama] = text

        print(
            f"{nama:15} = {text}"
        )

    except Exception as ex:

        print(
            f"{nama:15} = ERROR : {ex}"
        )

print("")
print("======================")
print("")

# ==========================================
# HASIL AKHIR
# ==========================================

print("===== JSON RESULT =====")
print("")

print(
    json.dumps(
        ocr_result,
        indent=2,
        ensure_ascii=False
    )
)

print("")
print("======================")
print("")
print("SELESAI")