<?php

declare(strict_types=1);

namespace Inpsyde\MultilingualPress\MediaLibrary;

use Inpsyde\Assets\Asset;
use Inpsyde\Assets\AssetManager;
use Inpsyde\Assets\Script;
use Inpsyde\Assets\Style;
use Inpsyde\MultilingualPress\Framework\PluginProperties;
use Inpsyde\MultilingualPress\Framework\Service\BootstrappableServiceProvider;
use Inpsyde\MultilingualPress\Framework\Service\Container;
use Inpsyde\MultilingualPress\MediaLibrary\BulkCopyAttachments\BulkCopyAttachmentsRequestHandler;
use Inpsyde\MultilingualPress\MediaLibrary\BulkCopyAttachments\BulkCopyAttachmentsSettingsView;

class ServiceProvider implements BootstrappableServiceProvider
{
    public const MODULE_ID = 'media-library';
    public const PARAMETER_CONFIG_MODULE_DIR_PATH = 'multilingualpress.MediaLibrary.ModuleDirPath';
    public const PARAMETER_CONFIG_MODULE_ASSETS_FACTORY = 'multilingualpress.MediaLibrary.assetsFactory';

    public const PARAMETER_CONFIG_BULK_ACTIONS_KEY_PREFIX = 'multilingualpress.MediaLibrary.bulkActionsKeyPrefix';
    public const PARAMETER_CONFIG_BULK_ACTIONS = 'multilingualpress.MediaLibrary.bulkActions';

    public const PARAMETER_CONFIG_SETTINGS_ALL_SETTINGS = 'multilingualpress.MediaLibrary.allSettings';
    public const PARAMETER_CONFIG_SETTINGS_TITLE = 'multilingualpress.MediaLibrary.settingsTitle';

    public const MODULE_SCRIPTS_HANDLER_NAME = 'multilingualpress-media-library';
    public const PARAMETER_CONFIG_SHOULD_ENQUEUE_MODULE_ASSETS = 'multilingualpress.MediaLibrary.shouldEnqueueModuleAssets';
    public const CONFIGURATION_NAME_FOR_URL_TO_MODULE_ASSETS = 'multilingualpress.MediaLibrary.urlToModuleAssets';

    /**
     * @inheritdoc
     */
    public function register(Container $container)
    {
        $container->share(
            self::PARAMETER_CONFIG_MODULE_DIR_PATH,
            static function (): string {
                return __DIR__;
            }
        );

        /**
         * The configuration of the URL to module assets folder.
         */
        $container->share(
            self::CONFIGURATION_NAME_FOR_URL_TO_MODULE_ASSETS,
            static function (Container $container): string {
                $pluginProperties = $container->get(PluginProperties::class);

                return $pluginProperties->dirUrl() . 'src/multilingualpress/MediaLibrary/public/';
            }
        );

        /**
         * Configuration to check if the current screen is the correct one to enqueue module assets.
         */
        $container->share(
            self::PARAMETER_CONFIG_SHOULD_ENQUEUE_MODULE_ASSETS,
            static function (): bool {
                global $pagenow;

                $postId = (int)filter_input(INPUT_GET, 'post', FILTER_SANITIZE_SPECIAL_CHARS);
                $isAttachmentEditScreen = $postId > 0 && get_post_type($postId) === 'attachment';

                return $pagenow === 'upload.php' || $isAttachmentEditScreen;
            }
        );

        $moduleDirPath = $container->get(self::PARAMETER_CONFIG_MODULE_DIR_PATH);

        require $moduleDirPath . '/BulkCopyAttachments/services.php';
        require $moduleDirPath . '/Settings/services.php';
    }

    /**
     * @inheritdoc
     */
    public function bootstrap(Container $container)
    {
        if (!is_admin()) {
            return;
        }

        $shouldEnqueueModuleAssets = $container->get(self::PARAMETER_CONFIG_SHOULD_ENQUEUE_MODULE_ASSETS);
        $urlToModuleAssetsFolder = $container->get(self::CONFIGURATION_NAME_FOR_URL_TO_MODULE_ASSETS);
        $this->registerAssets($shouldEnqueueModuleAssets, $urlToModuleAssetsFolder);

        $moduleDirPath = $container->get(self::PARAMETER_CONFIG_MODULE_DIR_PATH);

        require $moduleDirPath . '/BulkCopyAttachments/hooks.php';
        require $moduleDirPath . '/CopySingleAttachment/hooks.php';
    }

    /**
     * Sets up assets for module.
     *
     * @param bool $shouldEnqueueModuleAssets Whether should enqueue the assets.
     * @param string $urlToModuleAssetsFolder The url to assets folder.
     */
    protected function registerAssets(bool $shouldEnqueueModuleAssets, string $urlToModuleAssetsFolder): void
    {
        add_action(
            AssetManager::ACTION_SETUP,
            //phpcs:disable Inpsyde.CodeQuality.LineLength.TooLong
            static function (AssetManager $assetManager) use ($urlToModuleAssetsFolder, $shouldEnqueueModuleAssets) {
                $script = new Script(self::MODULE_SCRIPTS_HANDLER_NAME, "{$urlToModuleAssetsFolder}js/admin.min.js");
                $script
                    ->withDependencies('multilingualpress-admin')
                    ->withLocalize('mediaLibraryModule', [
                            'copySettings' => [
                                'relatedSiteSettingElementSelectorName' => '.multilingualpress-media-library-related-sites',
                                'bulkCopySettingsWrapperSelectorName' => '.multilingualpress-bulk-copy-media-setting',
                                'listViewSelectorName' => 'form#posts-filter',
                                'view' => [
                                    'toolbarWrapperSelectorName' => '.media-toolbar .media-toolbar-secondary',
                                    'action' => BulkCopyAttachmentsSettingsView::ACTION,
                                ],
                                'copy' => [
                                    'action' => BulkCopyAttachmentsRequestHandler::ACTION,
                                    'confirmationMessage' => __("You are about to copy the selected attachments to the selected remote sites and if exists under the same name, the media content will be overriden. This action cannot be undone.\n'Cancel' to stop, 'OK' to copy.", 'multilingualpress'),
                                    'noRemoteSitesSelectedMessage' => __('Please select the remote sites to copy', 'multilingualpress'),
                                    'noAttachmentsSelectedMessage' => __('Please select the media to copy', 'multilingualpress'),
                                    'successMessage' => __('Successfully Copied', 'multilingualpress'),
                                ],
                            ],
                        ])
                    ->forLocation(Asset::BACKEND)
                    ->canEnqueue(
                        static function () use ($shouldEnqueueModuleAssets): bool {
                            return $shouldEnqueueModuleAssets;
                        }
                    );

                $style = new Style(self::MODULE_SCRIPTS_HANDLER_NAME, "{$urlToModuleAssetsFolder}css/admin.min.css");
                $style
                    ->forLocation(Asset::BACKEND)
                    ->canEnqueue(
                        static function () use ($shouldEnqueueModuleAssets): bool {
                            return $shouldEnqueueModuleAssets;
                        }
                    );

                $assetManager->register($script, $style);
            }
            // phpcs:enable
        );
    }
}
