<?php
// SPDX-FileCopyrightText: IndieHosters <contact@indiehosters.net>
// SPDX-License-Identifier: AGPL-3.0-or-later

namespace OCA\CustomNav\Controller;

use OCA\CustomNav\Service\Manager;
use OCP\AppFramework\Controller;
use OCP\AppFramework\Http\Response;
use OCP\IRequest;
use OCP\IUserSession;
use OCP\AppFramework\Http\JSONResponse;

class SettingsController extends Controller
{
    protected Manager $manager;
    protected IUserSession $userSession;

    public function __construct(
        $appName,
        IRequest $request,
        Manager $manager,
        IUserSession $userSession
    ) {
        parent::__construct($appName, $request);

        $this->manager = $manager;
        $this->userSession = $userSession;
    }

    /**
     * @NoCSRFRequired
     */
    public function admin(array $apps, bool $disableUserEdit): Response
    {
        $this->manager->setDisableUserEdit($disableUserEdit);
        $overwrite = $this->manager->toOverwrite($apps);
        $this->manager->setSystemOverwrite($overwrite);
        return new JSONResponse($overwrite);
    }

    /**
     * @NoAdminRequired
     * @NoCSRFRequired
     */
    public function personal(array $apps): Response
    {
        $user = $this->userSession->getUser();
        $overwrite = $this->manager->toOverwrite($apps);
        $sysOverwrite = $this->manager->getSystemOverwrite();
        $userOverwrite = [];
        foreach ($overwrite as $appId => $appOverwrite) {
            if ($sysAppOverwrite = &$sysOverwrite[$appId] === null) {
                $userOverwrite[$appId] = $appOverwrite;
                continue;
            }
            $diff = array_diff_assoc($appOverwrite, $sysAppOverwrite);
            if ($diff != null) {
                $userOverwrite[$appId] = $diff;
            }
        }
        $this->manager->setUserOverwrite($user, $userOverwrite);
        return new JSONResponse([$apps, $userOverwrite]);
    }
}
