<?php

declare(strict_types = 1);

// {{{ License

// This file is part of GNU social - https://www.gnu.org/software/social
//
// GNU social is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// GNU social is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with GNU social.  If not, see <http://www.gnu.org/licenses/>.

// }}}

namespace Plugin\WebHooks\Controller;

use App\Core\Controller;
use App\Core\DB;
use App\Core\Form;
use function App\Core\I18n\_m;
use App\Core\Router;
use App\Util\Common;
use App\Util\Exception\ClientException;
use Functional as F;
use Plugin\WebHooks as P;
use Plugin\WebHooks\Entity as E;
use Symfony\Component\Form\Extension\Core\Type\SubmitType;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\HttpFoundation\Request;

class WebHooks extends Controller
{
    public static function setup()
    {
        $user  = Common::ensureLoggedIn();
        $hooks = F\reindex(DB::findBy(E\WebHook::class, ['actor_id' => $user->getId()]), fn (E\WebHook $wh) => $wh->getEvent());
        $form = Form::create([
            ['notifications', TextType::class, ['label' => _m('Trigger this hook when I recieve a notification'), 'data' => ($hooks['notifications'] ?? null)?->getTarget()]],
            ['subscriptions', TextType::class, ['label' => _m('Trigger this hook when someone subscribes to me'), 'data' => ($hooks['subscriptions'] ?? null)?->getTarget()]],
            ['save_webhooks', SubmitType::class, ['label' => _m('Submit')]],
        ], form_options: ['action' => Router::url(P\WebHooks::controller_route)]);

        return [
            '_template' => 'webhooks/settings.html.twig',
            'form_view' => $form->createView(),
            'form'      => $form,
            'hooks'     => $hooks,
        ];
    }

    public function onPost(Request $request)
    {
        $get_response = self::setup();
        $form         = $get_response['form'];
        $hooks        = $get_response['hooks'];

        $user = Common::user();
        if (\is_null($user)) {
            return Form::forceRedirect($form, $request);
        }

        $form->handleRequest($request);
        if ($form->isSubmitted() && $form->isValid()) {
            $data = $form->getData();
            unset($data['_next']);
            $error = false;
            foreach ($data as $key => $value) {
                if ($value !== '') {
                    $parts = parse_url($value);
                    if ($parts === false || ($parts['scheme'] ?? null) !== 'https' || ($parts['host'] ?? null) === Common::config('site', 'server')) {
                        $error = true;
                        break;
                    } else {
                        if (!isset($hooks[$key])) {
                            DB::persist(E\WebHook::create([
                                'actor_id' => $user->getId(),
                                'event'    => $key,
                                'target'   => $value,
                            ]));
                        } else {
                            $hooks[$key]->setTarget($value);
                        }
                    }
                } else {
                    $error = true;
                }
            }

            if (!$error) {
                DB::flush();
                return Form::forceRedirect($form, $request);
            } else {
                throw new ClientException(_m('Invalid form submission'));
            }
        }
        throw new ClientException(_m('Don\'t GET this page'));
    }
}
