<?php

namespace Velis\Dto\Common;

use ArrayIterator;
use IteratorAggregate;
use Traversable;
use Velis\Dto\BaseDto;
use Velis\Dto\Exceptions\ValidationException;
use Velis\Dto\Utility\Optional;
use Velis\Lang;
use Velis\Model\DataObject;

class TranslationsDto extends BaseDto implements IteratorAggregate
{
    public Optional|null|string $af;
    public Optional|null|string $ar;
    public Optional|null|string $az;
    public Optional|null|string $be;
    public Optional|null|string $bg;
    public Optional|null|string $bs;
    public Optional|null|string $cs;
    public Optional|null|string $de;
    public Optional|null|string $el;
    public Optional|null|string $en;
    public Optional|null|string $es;
    public Optional|null|string $et;
    public Optional|null|string $fi;
    public Optional|null|string $fr;
    public Optional|null|string $hr;
    public Optional|null|string $hu;
    public Optional|null|string $it;
    public Optional|null|string $ja;
    public Optional|null|string $ka;
    public Optional|null|string $kk;
    public Optional|null|string $lt;
    public Optional|null|string $lv;
    public Optional|null|string $mk;
    public Optional|null|string $mx;
    public Optional|null|string $nl;
    public Optional|null|string $no;
    public Optional|null|string $pl;
    public Optional|null|string $pt;
    public Optional|null|string $ro;
    public Optional|null|string $ru;
    public Optional|null|string $sk;
    public Optional|null|string $sl;
    public Optional|null|string $sr;
    public Optional|null|string $sv;
    public Optional|null|string $uk;
    public Optional|null|string $zh;

    public function getIterator(): Traversable
    {
        return new ArrayIterator($this->toArray());
    }

    /**
     * @throws ValidationException
     */
    public static function fromDto(BaseDto $obj): static
    {
        return static::fromArray($obj->toArray());
    }

    /**
     * @throws ValidationException
     */
    public static function fromModel(DataObject $model, ?string $field = 'name'): static
    {
        return static::fromArray($model->getArrayCopy(), $field);
    }

    /**
     * @param array<string, string> $data
     * @throws ValidationException
     */
    public static function fromArray(array $data, ?string $field = null, string $separator = '_'): static
    {
        $names = [];
        foreach (array_keys(Lang::getLanguages()) as $langKey) {
            $key = $field ? $field . $separator . $langKey : $langKey;
            if (array_key_exists($key, $data) && $data[$key] !== '') {
                $names[$langKey] = $data[$key];
            }
        }

        return parent::fromArray($names);
    }
}
