<?php

declare(strict_types = 1);

namespace Component\Posting\Form;

use App\Core\ActorLocalRoles;
use App\Core\Event;
use App\Core\Form;
use function App\Core\I18n\_m;
use App\Core\Router;
use App\Core\VisibilityScope;
use App\Entity\Actor;
use App\Util\Common;
use App\Util\Form\FormFields;
use Symfony\Component\Form\Extension\Core\Type\ChoiceType;
use Symfony\Component\Form\Extension\Core\Type\FileType;
use Symfony\Component\Form\Extension\Core\Type\HiddenType;
use Symfony\Component\Form\Extension\Core\Type\SubmitType;
use Symfony\Component\Form\Extension\Core\Type\TextareaType;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Validator\Constraints\Length;

class Posting
{
    public static function create(Request $request)
    {
        $actor = Common::actor();

        $placeholder_strings = ['How are you feeling?', 'Have something to share?', 'How was your day?'];
        Event::handle('PostingPlaceHolderString', [&$placeholder_strings]);
        $placeholder = $placeholder_strings[array_rand($placeholder_strings)];

        $initial_content = '';
        Event::handle('PostingInitialContent', [&$initial_content]);

        $available_content_types = [
            _m('Plain Text') => 'text/plain',
        ];
        Event::handle('PostingAvailableContentTypes', [&$available_content_types]);

        $in_targets = [];
        Event::handle('PostingFillTargetChoices', [$request, $actor, &$in_targets]);

        $context_actor = null;
        Event::handle('PostingGetContextActor', [$request, $actor, &$context_actor]);

        $form_params = [];
        if (!empty($in_targets)) { // @phpstan-ignore-line
            // Add "none" option to the first of choices
            $in_targets = array_merge([_m('Public') => 'public'], $in_targets);
            // Make the context actor the first In target option
            if (!\is_null($context_actor)) {
                foreach ($in_targets as $it_nick => $it_id) {
                    if ($it_id === $context_actor->getId()) {
                        unset($in_targets[$it_nick]);
                        $in_targets = array_merge([$it_nick => $it_id], $in_targets);
                        break;
                    }
                }
            }
            $form_params[] = ['in', ChoiceType::class, ['label' => _m('In:'), 'multiple' => false, 'expanded' => false, 'choices' => $in_targets]];
        }

        $visibility_options = [
            _m('Public')    => VisibilityScope::EVERYWHERE->value,
            _m('Local')     => VisibilityScope::LOCAL->value,
            _m('Addressee') => VisibilityScope::ADDRESSEE->value,
        ];
        if (!\is_null($context_actor) && $context_actor->isGroup()) { // @phpstan-ignore-line currently an open bug. See https://web.archive.org/web/20220226131651/https://github.com/phpstan/phpstan/issues/6234
            if ($actor->canModerate($context_actor)) {
                if ($context_actor->getRoles() & ActorLocalRoles::PRIVATE_GROUP) {
                    $visibility_options = array_merge([_m('Group') => VisibilityScope::GROUP->value], $visibility_options);
                } else {
                    $visibility_options[_m('Group')] = VisibilityScope::GROUP->value;
                }
            }
        }
        $form_params[] = ['visibility', ChoiceType::class, ['label' => _m('Visibility:'), 'multiple' => false, 'expanded' => false, 'choices' => $visibility_options]];

        $form_params[] = ['content', TextareaType::class, ['label' => _m('Content:'), 'data' => $initial_content, 'attr' => ['placeholder' => _m($placeholder)], 'constraints' => [new Length(['max' => Common::config('site', 'text_limit')])]]];
        $form_params[] = ['attachments', FileType::class, ['label' => _m('Attachments:'), 'multiple' => true, 'required' => false, 'invalid_message' => _m('Attachment not valid.')]];
        $form_params[] = FormFields::language($actor, $context_actor, label: _m('Note language'), help: _m('The selected language will be federated and added as a lang attribute, preferred language can be set up in settings'));

        if (\count($available_content_types) > 1) {
            $form_params[] = ['content_type', ChoiceType::class,
                [
                    'label'   => _m('Text format:'), 'multiple' => false, 'expanded' => false,
                    'data'    => $available_content_types[array_key_first($available_content_types)],
                    'choices' => $available_content_types,
                ],
            ];
        } else {
            $form_params[] = ['content_type', HiddenType::class, ['data' => $available_content_types[array_key_first($available_content_types)]]];
        }

        Event::handle('PostingAddFormEntries', [$request, $actor, &$form_params]);

        $form_params[] = ['post_note', SubmitType::class, ['label' => _m('Post')]];

        return Form::create($form_params, form_options: ['action' => Router::url(\Component\Posting\Posting::route)]);
    }
}
