<?php

declare(strict_types = 1);

namespace Plugin\UnboundGroup\Controller;

use App\Core\Controller;
use App\Core\DB;
use App\Core\Form;
use function App\Core\I18n\_m;
use App\Entity as E;
use App\Util\Common;
use App\Util\Exception\ClientException;
use Component\Subscription\Subscription;
use Plugin\ActivityPub\Util\Explorer;
use Plugin\UnboundGroup\Entity\activitypubGroupUnbound;
use Symfony\Component\Form\Extension\Core\Type\ChoiceType;
use Symfony\Component\Form\Extension\Core\Type\SubmitType;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\HttpFoundation\Request;

class GroupSettings extends Controller
{
    /**
     * Manage the gs:unbound state
     */
    public static function groupUnbound(Request $request, E\Actor $target, string $details_id)
    {
        $actor = Common::ensureLoggedIn()->getActor();
        if (!$actor->canModerate($target)) {
            throw new ClientException(_m('You don\'t have enough permissions to edit {nickname}\'s settings', ['{nickname}' => $target->getNickname()]));
        }

        $unbound_options = [
            _m('Default') => null,
            _m('True')    => true,
            _m('False')   => false,
        ];

        $obj = DB::findOneBy(activitypubGroupUnbound::class, ['actor_id' => $target->getId()], return_null: true);

        $form_definition = [
            ['new_state', ChoiceType::class, ['label' => _m('Unbound:'), 'multiple' => false, 'expanded' => false, 'choices' => $unbound_options, 'data' => $obj?->getUnbound()]],
            [$save_unbound_state_form_name = 'save_group_links', SubmitType::class, ['label' => _m('Save state')]],
        ];

        $unbound_state_form = Form::create($form_definition);

        if ($request->getMethod() === 'POST' && $request->request->has($save_unbound_state_form_name)) {
            $unbound_state_form->handleRequest($request);
            if ($unbound_state_form->isSubmitted() && $unbound_state_form->isValid()) {
                $new_state  = $unbound_state_form->getData()['new_state'];
                $update_obj = activitypubGroupUnbound::createOrUpdate(obj: $obj, args: [
                    'actor_id' => $target->getId(),
                    'unbound'  => $new_state,
                ]);
                if (\is_null($obj)) {
                    DB::persist($update_obj);
                }
                DB::flush();
                Form::forceRedirect($unbound_state_form, $request);
            }
        }

        return [
            '_template'          => 'self_tags_settings.fragment.html.twig',
            'add_self_tags_form' => $unbound_state_form->createView(),
        ];
    }
    /**
     * Manage the linksTo collection of a Group or Organisation Actor
     */
    public static function groupLinks(Request $request, E\Actor $target, string $details_id)
    {
        $actor = Common::ensureLoggedIn()->getActor();
        if (!$actor->canModerate($target)) {
            throw new ClientException(_m('You don\'t have enough permissions to edit {nickname}\'s settings', ['{nickname}' => $target->getNickname()]));
        }

        $form_definition = [
            ['new_link', TextType::class, ['label' => _m('Link to'), 'required' => true, 'help' => _m('Enter the URI.')]],
            [$add_link_to_form_name = 'save_group_links', SubmitType::class, ['label' => _m('Add link')]],
        ];

        $add_link_to_form = Form::create($form_definition);

        if ($request->getMethod() === 'POST' && $request->request->has($add_link_to_form_name)) {
            $add_link_to_form->handleRequest($request);
            if ($add_link_to_form->isSubmitted() && $add_link_to_form->isValid()) {
                if (Common::isValidHttpUrl($new_uri = $add_link_to_form->getData()['new_link'])) {
                    $new_link = Explorer::getOneFromUri($new_uri);

                    $unbound = DB::findOneBy(activitypubGroupUnbound::class, ['actor_id' => $new_link->getId()], return_null: true);
                    if ($unbound?->getUnbound() ?? true) {
                        if (\is_null(Subscription::subscribe(subject: $target, object: $new_link, source: 'ActivityPub via FEP-2100'))) {
                            throw new ClientException(_m('This group is already linked from {nickname}', ['{nickname}' => $new_link->getNickname()]));
                        }
                        Subscription::refreshSubscriptionCount($target, $new_link);
                    }
                    Form::forceRedirect($add_link_to_form, $request);
                } else {
                    throw new ClientException(_m('Invalid URI given.'));
                }
            }
        }

        return [
            '_template'          => 'self_tags_settings.fragment.html.twig',
            'add_self_tags_form' => $add_link_to_form->createView(),
        ];
    }
}
