<?php
namespace Helpers\ExportTo;

use Entity\Model\Hastutil;
use Helpers\Fichier\Fichier;
use Helpers\Trad\ITrad;
use Helpers\User\User;
use Psr\Container\ContainerInterface;
use Skeleton\Router;

class EmailCsvService
{
    private ITrad $trad;
    private Router $router;
    private \PDO $pdo;

    public function __construct(ContainerInterface $container)
    {
        $this->router = $container->get(Router::class);
        $this->trad = $container->get(ITrad::class);
        $this->pdo = $container->get(\PDO::class);
    }

    /**
     * @param iterable<array<string>> $listRow
     * @param array<string> $header
     */
    public function sendCsv(
        string $fileBaseName,
        $listRow,
        ?callable $fnFormat,
        array $header
    ) :void {
        $fileName = Fichier::generateFileName($fileBaseName, 'csv');
        $file = CsvRes::touch(Fichier::getDirExport() . $fileName)
            ->addRow($header);
        
        foreach ($listRow as $row) {
            if (empty($row)) {// TODO : pdo odbc iterator generate 20000 empty array, why ?
                continue;
            }
            
            if ($fnFormat !== null) {
                $row = $fnFormat($row);
            }
            $file->addRow($row);
        }

        unset($file);

        \Helpers\ExportTo\Outils::sendExportEmailAsync(
            $fileName,
            (new Hastutil($this->pdo))
            ->find((new User())->getCodeUser())['EMAIL'] ?? '',
            $this->router,
            $this->trad
        );
    }
}
