<?php

declare(strict_types=1);

namespace Seka\Portal\Modul\Statistiky\Services\Transformators;

use Seka\Portal\Modul\Statistiky\Services\Import\File;
use Seka\Portal\Modul\Statistiky\Entities\Zaznam\DTOs\ImportLineDTO;

/**
 * Class CSVDataTransformator
 *
 * @package Seka\Portal\Modul\Statistiky\Services\Transformators
 */
final class CSVDataTransformator implements DataTransformatorContract
{
    /**
     * @param \Seka\Portal\Modul\Statistiky\Services\Import\File $file
     *
     * @return \Seka\Portal\Modul\Statistiky\Entities\Zaznam\DTOs\ImportLineDTO[]
     */
    public function transform(File $file): array
    {
        $data = array_map('str_getcsv', $file->content());

        return $this->mapArrayToObjects($data);
    }

    /**
     * @param array $data
     *
     * @return ImportLineDTO[]
     */
    private function mapArrayToObjects(array $data): array
    {
        $out = [];
        $keys = $data[0];

        // premenovanie klucov z formatu aaa_bbb na format aaaBbb
        foreach ($keys as &$key) {
            $key = lcfirst(str_replace(' ', '', ucwords(str_replace('_', ' ', $key))));
        }

        for ($line = 1; $line < count($data); ++$line) {
            $mapped = array_combine($keys, $data[$line]);
            $out[] = new ImportLineDTO($mapped);
        }

        return $out;
    }
}
