<?php

declare(strict_types=1);

namespace Inpsyde\MultilingualPress\MediaLibrary;

use Inpsyde\MultilingualPress\Asset\AssetFactory;
use Inpsyde\MultilingualPress\Core\Locations;
use Inpsyde\MultilingualPress\Framework\Asset\AssetException;
use Inpsyde\MultilingualPress\Framework\Asset\AssetManager;
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;

use function Inpsyde\MultilingualPress\isWpDebugMode;

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_IS_MEDIA_LIBRARY_SCREEN = 'multilingualpress.MediaLibrary.isMediaLibraryScreen';

    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';

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

        $container->share(
            self::PARAMETER_CONFIG_MODULE_ASSETS_FACTORY,
            static function (Container $container): AssetFactory {
                $pluginProperties = $container->get(PluginProperties::class);
                $pathToPublic = "{$pluginProperties->dirPath()}src/multilingualpress/MediaLibrary/public";
                $urlToPublic = "{$pluginProperties->dirUrl()}src/multilingualpress/MediaLibrary/public";

                $locations = new Locations();
                $locations
                    ->add('css', "{$pathToPublic}/css", "{$urlToPublic}/css")
                    ->add('js', "{$pathToPublic}/js", "{$urlToPublic}/js");

                return new AssetFactory($locations);
            }
        );

        /**
         * Configuration to check if the current screen is upload.php.
         */
        $container->share(
            self::PARAMETER_CONFIG_IS_MEDIA_LIBRARY_SCREEN,
            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;
        }

        $isMediaLibraryScreen = $container->get(self::PARAMETER_CONFIG_IS_MEDIA_LIBRARY_SCREEN);

        if ($isMediaLibraryScreen) {
            $assetManager = $container->get(AssetManager::class);
            $assetFactory = $container->get(self::PARAMETER_CONFIG_MODULE_ASSETS_FACTORY);
            $this->enqueueAssets($assetManager, $assetFactory);
        }

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

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

    /**
     * Will enqueue the module assets.
     *
     * @param AssetManager $assetManager
     * @param AssetFactory $assetFactory
     */
    protected function enqueueAssets(AssetManager $assetManager, AssetFactory $assetFactory): void
    {
        $moduleId = self::MODULE_ID;
        $assetName = "multilingualpress-{$moduleId}";

        $styles = $assetFactory->createInternalStyle($assetName, 'admin.min.css');
        $scripts = $assetFactory->createInternalScript($assetName, 'admin.min.js', ['multilingualpress-admin']);

        $assetManager->registerStyle($styles)->registerScript($scripts);

        try {
            $assetManager->enqueueStyle($assetName);
            $assetManager->enqueueScriptWithData(
                $assetName,
                'mediaLibraryModule',
                //phpcs:disable Inpsyde.CodeQuality.LineLength.TooLong
                [
                    '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'),
                        ],
                    ],
                ]
                // phpcs:enable
            );
        } catch (AssetException $exc) {
            if (isWpDebugMode()) {
                throw $exc;
            }
        }
    }
}
