<?php
namespace Veno\QrCdr\Lib;

/**
 * QR Code Reed-Solomon Manager (Private Fork for Veno QrCdr)
 *
 * Caches initialized QrcdrRsItem objects to improve performance.
 *
 * @package   QrCdr
 * @version   1.1.4-patched
 */

if ( ! defined( 'ABSPATH' ) && ! defined( 'QRCDR_OPEN_ACCESS' ) ) {
	exit;
}

class QrcdrRs {

	/**
	 * Cache of initialized QrcdrRsItem instances.
	 * @var QrcdrRsItem[]
	 */
	public static $items = array();

	/**
	 * Initialize or retrieve a Reed-Solomon codec from cache.
	 *
	 * @param int $symbol_size  Symbol size in bits (usually 8).
	 * @param int $gf_poly      Galois Field polynomial.
	 * @param int $fcr          First consecutive root.
	 * @param int $prim         Primitive element.
	 * @param int $num_roots    Number of generator roots (parity symbols).
	 * @param int $pad          Padding for shortened blocks.
	 * @return QrcdrRsItem|null The codec item or null on error.
	 */
	public static function init_rs( $symbol_size, $gf_poly, $fcr, $prim, $num_roots, $pad ) {
		foreach ( self::$items as $rs_item ) {
			if ( $pad !== $rs_item->pad ) {
				continue;
			}
			if ( $num_roots !== $rs_item->nroots ) {
				continue;
			}
			if ( $symbol_size !== $rs_item->mm ) {
				continue;
			}
			if ( $gf_poly !== $rs_item->gfpoly ) {
				continue;
			}
			if ( $fcr !== $rs_item->fcr ) {
				continue;
			}
			if ( $prim !== $rs_item->prim ) {
				continue;
			}

			return $rs_item;
		}

		$rs_item = QrcdrRsItem::init_rs_char( $symbol_size, $gf_poly, $fcr, $prim, $num_roots, $pad );
		array_unshift( self::$items, $rs_item );

		return $rs_item;
	}
}
