#!/bin/bash

# ============================================
#  Be Inhouse — Afbeeldingen resizen
#  Zet alle afbeeldingen in de map 'input'
#  en dubbelklik dit bestand om te starten.
# ============================================

cd "$(dirname "$0")"

INPUT_FOLDER="./input"
OUTPUT_FOLDER="./output"

# Controleer of ImageMagick is geïnstalleerd
if ! command -v convert &> /dev/null; then
  osascript -e 'display dialog "ImageMagick is niet geïnstalleerd. Vraag Bram om dit eenmalig te installeren via Terminal." buttons {"OK"} default button "OK" with icon stop with title "Be Inhouse — Fout"'
  exit 1
fi

# Controleer of de input map bestaat
if [ ! -d "$INPUT_FOLDER" ]; then
  osascript -e 'display dialog "De map \"input\" bestaat niet. Maak deze aan naast dit bestand en zet er je afbeeldingen in." buttons {"OK"} default button "OK" with icon stop with title "Be Inhouse — Fout"'
  exit 1
fi

# Tel het aantal afbeeldingen
COUNT=$(find "$INPUT_FOLDER" -maxdepth 1 \( -iname "*.jpg" -o -iname "*.jpeg" -o -iname "*.png" \) | wc -l | tr -d ' ')

if [ "$COUNT" -eq 0 ]; then
  osascript -e 'display dialog "Er staan geen afbeeldingen in de map \"input\". Voeg eerst JPG of PNG bestanden toe." buttons {"OK"} default button "OK" with icon caution with title "Be Inhouse — Geen afbeeldingen"'
  exit 1
fi

# Bevestiging tonen
osascript -e "display dialog \"$COUNT afbeeldingen gevonden. Klik op Start om ze te verwerken naar 1600x1200 pixels (max 1 MB).\" buttons {\"Annuleren\", \"Start\"} default button \"Start\" with title \"Be Inhouse — Afbeeldingen resizen\""

if [ $? -ne 0 ]; then
  exit 0
fi

# Output map aanmaken
mkdir -p "$OUTPUT_FOLDER"

# Afbeeldingen verwerken
DONE=0
for img in "$INPUT_FOLDER"/*.jpg "$INPUT_FOLDER"/*.jpeg "$INPUT_FOLDER"/*.png \
           "$INPUT_FOLDER"/*.JPG "$INPUT_FOLDER"/*.JPEG "$INPUT_FOLDER"/*.PNG; do
  [ -f "$img" ] || continue
  filename=$(basename "$img")

  # Resize met kwaliteit 85 als startpunt
  convert "$img" \
    -gravity Center \
    -resize 1600x1200^ \
    -extent 1600x1200 \
    -quality 85 \
    "$OUTPUT_FOLDER/$filename"

  # Verlaag kwaliteit stapsgewijs totdat bestand onder 1 MB is
  FILESIZE=$(stat -f%z "$OUTPUT_FOLDER/$filename")
  QUALITY=75
  while [ "$FILESIZE" -gt 1048576 ] && [ "$QUALITY" -gt 20 ]; do
    convert "$img" \
      -gravity Center \
      -resize 1600x1200^ \
      -extent 1600x1200 \
      -quality $QUALITY \
      "$OUTPUT_FOLDER/$filename"
    FILESIZE=$(stat -f%z "$OUTPUT_FOLDER/$filename")
    QUALITY=$((QUALITY - 10))
  done

  DONE=$((DONE + 1))
done

# Klaar-melding
osascript -e "display dialog \"Klaar! $DONE afbeeldingen zijn opgeslagen in de map \\\"output\\\".\" buttons {\"OK\"} default button \"OK\" with title \"Be Inhouse — Gereed\""

# Open de output map automatisch
open "$OUTPUT_FOLDER"
