<?php

/**
 * JCOGS Image Pro Filter
 * ======================
 * A Face Detection filter wrapper for the Pro addon.
 * 
 * @category   ExpressionEngine Add-on
 * @package    JCOGS Image Pro
 * @author     JCOGS Design <contact@jcogs.net>
 * @copyright  Copyright (c) 2021 - 2025 JCOGS Design
 * @license    https://jcogs.net/add-ons/license/jcogs_img_pro
 * @version    2.0.6
 * @link       https://JCOGS.net/
 * @since      2.0.0
 */

namespace JCOGSDesign\JCOGSImagePro\Filters;

use Imagine\Filter\FilterInterface;
use Imagine\Image\ImageInterface;
use JCOGSDesign\JCOGSImagePro\Filters\Gd\FaceDetect as GdFaceDetect;

/**
 * A Face Detection filter wrapper that respects face_detect_sensitivity parameter
 */
class FaceDetectFilter implements FilterInterface
{
    /**
     * @var int Face detection sensitivity (1-9)
     */
    private $sensitivity;
    
    /**
     * @var string Action to perform (highlight, blur, mask)
     */
    private $action;
    
    /**
     * @var int Strength of the effect (0-100)
     */
    private $strength;
    
    /**
     * @var array|null Cached face regions
     */
    private $cached_regions;

    /**
     * Constructs FaceDetectFilter
     *
     * @param int $sensitivity Face detection sensitivity (1-9), defaults to 5
     * @param string $action Action to perform, defaults to 'highlight'
     * @param int $strength Strength of effect, defaults to 50
     * @param array|null $cached_regions Pre-detected face regions (optional)
     */
    public function __construct(int $sensitivity = 5, string $action = 'highlight', int $strength = 50, ?array $cached_regions = null)
    {
        $this->sensitivity = max(1, min(9, $sensitivity));
        $this->action = $action;
        $this->strength = $strength;
        $this->cached_regions = $cached_regions;
    }

    /**
     * Apply face detection filter to image
     * 
     * @param ImageInterface $image Source image
     * @return ImageInterface Processed image
     */
    public function apply(ImageInterface $image): ImageInterface
    {
        // Use GD implementation for face detection
        if ($image instanceof \Imagine\Gd\Image) {
            $gd_filter = new GdFaceDetect();
            
            // Build parameters array
            $parameters = [
                'action' => $this->action,
                'strength' => $this->strength,
                'cached_face_regions' => $this->cached_regions,
                'face_detect_sensitivity' => $this->sensitivity
            ];
            
            // Apply filter - returns PNG string
            $result_png = $gd_filter->apply($image, $parameters);
            
            // Convert result back to Imagine image
            $imagine = new \Imagine\Gd\Imagine();
            return $imagine->load($result_png);
        }
        
        // For non-GD image types, return unchanged (could implement Imagick/Gmagick support later)
        return $image;
    }
}
