<?php

namespace App\User\Dto;

use App\User\Framework\Entity\PreferenceOption;
use App\User\Framework\Entity\User;
use Symfony\Component\Security\Core\User\UserInterface;

class UserPreferencesFactory
{
    public static function createFromArray(array $data): UserPreferences
    {
        return new UserPreferences(
            resolution: static::getArrayValue($data, 'resolution'),
            codec: static::getArrayValue($data, 'codec'),
            language: static::getArrayValue($data, 'language'),
            provider: static::getArrayValue($data, 'provider'),
            quality: static::getArrayValue($data, 'quality'),
        );
    }

    /** @param User $user */
    public static function createFromUser(UserInterface $user): UserPreferences
    {
        return new UserPreferences(
            resolution: self::getValue($user, 'resolution'),
            codec: self::getValue($user, 'codec'),
            language: self::getValue($user, 'language'),
            provider: self::getValue($user, 'provider'),
            quality: self::getValue($user, 'quality'),
        );
    }

    /** @param User $user */
    private static function getValue(UserInterface $user, string $preferenceId)
    {
        $value = $user->getUserPreference($preferenceId)->getPreferenceValue();
        if ($value === "") {
            return null;
        }
        $value = explode(',', $value);
        return $value;
    }

    private static function getArrayValue(array $data, string $key): array|null
    {
        if (!array_key_exists($key, $data)) {
            return null;
        }

        if ("" === $data[$key]) {
            return null;
        }

        if (true === is_string($data[$key])) {
            return [$data[$key]];
        }

        return $data[$key];
    }
}
