<?php
namespace Incoviba\Service\Contabilidad\Cartola;

use InvalidArgumentException;
use Psr\Http\Message\UploadedFileInterface;
use Incoviba\Common\Ideal\Cartola\Banco;

trait withSubBancos
{
    protected array $subBancos;
    public function registerSub(Banco $sub): self
    {
        $this->subBancos []= $sub;
        return $this;
    }
    public function getSubBanco(string $filename): Banco
    {
        foreach ($this->subBancos as $subBanco) {
            if ($subBanco->is($filename)) {
                return $subBanco;
            }
        }
        return $this;
    }
    public function process(UploadedFileInterface $file): array
    {
        $filename = $this->processUploadedFile($file);
        try {
            $subBanco = $this->getSubBanco($filename);
            $data = $subBanco->processFile($filename);
            return $subBanco->mapColumns($data);
        } catch (InvalidArgumentException) {
            $data = parent::processFile($filename);
            return $this->mapColumns($data);
        }
    }
}
