<?php

namespace App\Manager;

use App\Entity\AppSettings;
use Doctrine\ORM\EntityManagerInterface;

class AppSettingsManager
{
    private const string DEFAULT_MANGA_DIRECTORY = '/manga_data';
    private const string DEFAULT_IMAGE_DIRECTORY = '/image_data';

    public function __construct(private readonly EntityManagerInterface $entityManager)
    {
    }

    public function getSettings(): AppSettings
    {
        $settings = $this->entityManager->getRepository(AppSettings::class)->findOneBy([]);
        if (!$settings) {
            $settings = $this->createDefaultSettings();
        }

        return $settings;
    }

    public function updateSettings(AppSettings $newSettings): void
    {
        $settings = $this->entityManager->getRepository(AppSettings::class)->findOneBy([]);
        if (!$settings) {
            $settings = new AppSettings();
        }

        $settings->setMangaDirectory($newSettings->getMangaDirectory());
        $settings->setImageDirectory($newSettings->getImageDirectory());

        $this->entityManager->persist($settings);
        $this->entityManager->flush();
    }

    private function createDefaultSettings(): AppSettings
    {
        $settings = new AppSettings();
        $settings->setMangaDirectory(self::DEFAULT_MANGA_DIRECTORY);
        $settings->setImageDirectory(self::DEFAULT_IMAGE_DIRECTORY);

        $this->entityManager->persist($settings);
        $this->entityManager->flush();

        return $settings;
    }
}
