<?php
defined('TYPO3_MODE') || die();

# ----- # ----- # ----- # ----- # ----- # ----- # ----- # ----- # ----- #

// Windows compatibility

if (!function_exists('strptime')) {
    require_once(\TYPO3\CMS\Core\Utility\ExtensionManagementUtility::extPath('meilisearch') . 'Resources/Private/Php/strptime/strptime.php');
}

(function () {

    # ----- # ----- # ----- # ----- # ----- # ----- # ----- # ----- # ----- #
    // registering Index Queue page indexer helpers
    $GLOBALS['TYPO3_CONF_VARS']['EXTCONF']['meilisearch']['Indexer']['indexPageSubstitutePageDocument'][\WapplerSystems\Meilisearch\AdditionalFieldsIndexer::class] = \WapplerSystems\Meilisearch\AdditionalFieldsIndexer::class;

    \WapplerSystems\Meilisearch\IndexQueue\FrontendHelper\Manager::registerFrontendHelper(
        'findUserGroups',
        \WapplerSystems\Meilisearch\IndexQueue\FrontendHelper\UserGroupDetector::class
    );

    \WapplerSystems\Meilisearch\IndexQueue\FrontendHelper\Manager::registerFrontendHelper(
        'indexPage',
        \WapplerSystems\Meilisearch\IndexQueue\FrontendHelper\PageIndexer::class
    );


    # ----- # ----- # ----- # ----- # ----- # ----- # ----- # ----- # ----- #

    // page module plugin settings summary

    $GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['cms/layout/class.tx_cms_layout.php']['list_type_Info']['meilisearch_pi_results']['meilisearch'] = \WapplerSystems\Meilisearch\Controller\Backend\PageModuleSummary::class . '->getSummary';

    # ----- # ----- # ----- # ----- # ----- # ----- # ----- # ----- # ----- #

    // register search components

    \WapplerSystems\Meilisearch\Search\SearchComponentManager::registerSearchComponent(
        'access',
        \WapplerSystems\Meilisearch\Search\AccessComponent::class
    );

    \WapplerSystems\Meilisearch\Search\SearchComponentManager::registerSearchComponent(
        'relevance',
        \WapplerSystems\Meilisearch\Search\RelevanceComponent::class
    );

    \WapplerSystems\Meilisearch\Search\SearchComponentManager::registerSearchComponent(
        'sorting',
        \WapplerSystems\Meilisearch\Search\SortingComponent::class
    );

    \WapplerSystems\Meilisearch\Search\SearchComponentManager::registerSearchComponent(
        'debug',
        \WapplerSystems\Meilisearch\Search\DebugComponent::class
    );

    \WapplerSystems\Meilisearch\Search\SearchComponentManager::registerSearchComponent(
        'analysis',
        \WapplerSystems\Meilisearch\Search\AnalysisComponent::class
    );

    \WapplerSystems\Meilisearch\Search\SearchComponentManager::registerSearchComponent(
        'highlighting',
        \WapplerSystems\Meilisearch\Search\HighlightingComponent::class
    );

    \WapplerSystems\Meilisearch\Search\SearchComponentManager::registerSearchComponent(
        'spellchecking',
        \WapplerSystems\Meilisearch\Search\SpellcheckingComponent::class
    );

    \WapplerSystems\Meilisearch\Search\SearchComponentManager::registerSearchComponent(
        'faceting',
        \WapplerSystems\Meilisearch\Search\FacetingComponent::class
    );

    \WapplerSystems\Meilisearch\Search\SearchComponentManager::registerSearchComponent(
        'statistics',
        \WapplerSystems\Meilisearch\Search\StatisticsComponent::class
    );

    \WapplerSystems\Meilisearch\Search\SearchComponentManager::registerSearchComponent(
        'lastSearches',
        \WapplerSystems\Meilisearch\Search\LastSearchesComponent::class
    );

    \WapplerSystems\Meilisearch\Search\SearchComponentManager::registerSearchComponent(
        'elevation',
        \WapplerSystems\Meilisearch\Search\ElevationComponent::class
    );

    # ----- # ----- # ----- # ----- # ----- # ----- # ----- # ----- # ----- #

    // adding scheduler tasks

    $GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['scheduler']['tasks'][\WapplerSystems\Meilisearch\Task\ReIndexTask::class] = [
        'extension' => 'meilisearch',
        'title' => 'LLL:EXT:meilisearch/Resources/Private/Language/locallang.xlf:reindex_title',
        'description' => 'LLL:EXT:meilisearch/Resources/Private/Language/locallang.xlf:reindex_description',
        'additionalFields' => \WapplerSystems\Meilisearch\Task\ReIndexTaskAdditionalFieldProvider::class
    ];

    $GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['scheduler']['tasks'][\WapplerSystems\Meilisearch\Task\IndexQueueWorkerTask::class] = [
        'extension' => 'meilisearch',
        'title' => 'LLL:EXT:meilisearch/Resources/Private/Language/locallang.xlf:indexqueueworker_title',
        'description' => 'LLL:EXT:meilisearch/Resources/Private/Language/locallang.xlf:indexqueueworker_description',
        'additionalFields' => \WapplerSystems\Meilisearch\Task\IndexQueueWorkerTaskAdditionalFieldProvider::class
    ];

    if (!is_array($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['scheduler']['tasks'][\TYPO3\CMS\Scheduler\Task\TableGarbageCollectionTask::class]['options']['tables']['tx_meilisearch_statistics'])) {
        $GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['scheduler']['tasks'][\TYPO3\CMS\Scheduler\Task\TableGarbageCollectionTask::class]['options']['tables']['tx_meilisearch_statistics'] = [
            'dateField' => 'tstamp',
            'expirePeriod' => 180
        ];
    }

    # ----- # ----- # ----- # ----- # ----- # ----- # ----- # ----- # ----- #

    // registering the eID scripts
    // TODO move to suggest form modifier
    $GLOBALS['TYPO3_CONF_VARS']['FE']['eID_include']['tx_meilisearch_api'] = 'EXT:meilisearch/Classes/Eid/Api.php';

    # ----- # ----- # ----- # ----- # ----- # ----- # ----- # ----- # ----- #

    // add custom meilisearch content objects

    $GLOBALS['TYPO3_CONF_VARS']['FE']['ContentObjects'][\WapplerSystems\Meilisearch\ContentObject\Multivalue::CONTENT_OBJECT_NAME]
        = \WapplerSystems\Meilisearch\ContentObject\Multivalue::class;

    $GLOBALS['TYPO3_CONF_VARS']['FE']['ContentObjects'][\WapplerSystems\Meilisearch\ContentObject\Content::CONTENT_OBJECT_NAME]
        = \WapplerSystems\Meilisearch\ContentObject\Content::class;

    $GLOBALS['TYPO3_CONF_VARS']['FE']['ContentObjects'][\WapplerSystems\Meilisearch\ContentObject\Relation::CONTENT_OBJECT_NAME]
        = \WapplerSystems\Meilisearch\ContentObject\Relation::class;

    $GLOBALS['TYPO3_CONF_VARS']['FE']['ContentObjects'][\WapplerSystems\Meilisearch\ContentObject\Classification::CONTENT_OBJECT_NAME]
        = \WapplerSystems\Meilisearch\ContentObject\Classification::class;


    # ----- # ----- # ----- # ----- # ----- # ----- # ----- # ----- # ----- #

    // Register cache for frequent searches

    if (!is_array($GLOBALS['TYPO3_CONF_VARS']['SYS']['caching']['cacheConfigurations']['tx_meilisearch'])) {
        $GLOBALS['TYPO3_CONF_VARS']['SYS']['caching']['cacheConfigurations']['tx_meilisearch'] = [];
    }
    // Caching framework meilisearch
    if (!is_array($GLOBALS['TYPO3_CONF_VARS']['SYS']['caching']['cacheConfigurations']['tx_meilisearch_configuration'])) {
        $GLOBALS['TYPO3_CONF_VARS']['SYS']['caching']['cacheConfigurations']['tx_meilisearch_configuration'] = [];
    }

    if (!isset($GLOBALS['TYPO3_CONF_VARS']['SYS']['caching']['cacheConfigurations']['tx_meilisearch_configuration']['backend'])) {
        $GLOBALS['TYPO3_CONF_VARS']['SYS']['caching']['cacheConfigurations']['tx_meilisearch_configuration']['backend'] = \TYPO3\CMS\Core\Cache\Backend\Typo3DatabaseBackend::class;
    }

    if (!isset($GLOBALS['TYPO3_CONF_VARS']['SYS']['caching']['cacheConfigurations']['tx_meilisearch_configuration']['options'])) {
        // default life time one day
        $GLOBALS['TYPO3_CONF_VARS']['SYS']['caching']['cacheConfigurations']['tx_meilisearch_configuration']['options'] = ['defaultLifetime' => 60 * 60 * 24];
    }

    if (!isset($GLOBALS['TYPO3_CONF_VARS']['SYS']['caching']['cacheConfigurations']['tx_meilisearch_configuration']['groups'])) {
        $GLOBALS['TYPO3_CONF_VARS']['SYS']['caching']['cacheConfigurations']['tx_meilisearch_configuration']['groups'] = ['all'];
    }

    # ----- # ----- # ----- # ----- # ----- # ----- # ----- # ----- # ----- #
    /* @var \WapplerSystems\Meilisearch\System\Configuration\ExtensionConfiguration $extensionConfiguration */
    $extensionConfiguration = \TYPO3\CMS\Core\Utility\GeneralUtility::makeInstance(
        \WapplerSystems\Meilisearch\System\Configuration\ExtensionConfiguration::class
    );

    # ----- # ----- # ----- # ----- # ----- # ----- # ----- # ----- # ----- #

    if (!isset($GLOBALS['TYPO3_CONF_VARS']['EXTCONF']['meilisearch']['searchResultClassName '])) {
        $GLOBALS['TYPO3_CONF_VARS']['EXTCONF']['meilisearch']['searchResultClassName '] = \WapplerSystems\Meilisearch\Domain\Search\ResultSet\Result\SearchResult::class;
    }

    if (!isset($GLOBALS['TYPO3_CONF_VARS']['EXTCONF']['meilisearch']['searchResultSetClassName '])) {
        $GLOBALS['TYPO3_CONF_VARS']['EXTCONF']['meilisearch']['searchResultSetClassName '] = \WapplerSystems\Meilisearch\Domain\Search\ResultSet\SearchResultSet::class;
    }

    if (!isset($GLOBALS['TYPO3_CONF_VARS']['LOG']['WapplerSystems']['Meilisearch']['writerConfiguration'])) {
        $context = \TYPO3\CMS\Core\Utility\GeneralUtility::getApplicationContext();
        if ($context->isProduction()) {
            $logLevel = \TYPO3\CMS\Core\Log\LogLevel::ERROR;
        } elseif ($context->isDevelopment()) {
            $logLevel = \TYPO3\CMS\Core\Log\LogLevel::DEBUG;
        } else {
            $logLevel = \TYPO3\CMS\Core\Log\LogLevel::INFO;
        }
        $GLOBALS['TYPO3_CONF_VARS']['LOG']['WapplerSystems']['Meilisearch']['writerConfiguration'] = [
            $logLevel => [
                \TYPO3\CMS\Core\Log\Writer\FileWriter::class => [
                    'logFileInfix' => 'meilisearch'
                ]
            ],
        ];
    }

    # ----- # ----- # ----- # ----- # ----- # ----- # ----- # ----- # ----- #

    \TYPO3\CMS\Extbase\Utility\ExtensionUtility::configurePlugin(
        'WapplerSystems.meilisearch',
        'pi_results',
        [
            'Search' => 'results,form,detail'
        ],
        [
            'Search' => 'results'
        ]
    );

    \TYPO3\CMS\Extbase\Utility\ExtensionUtility::configurePlugin(
        'WapplerSystems.meilisearch',
        'pi_search',
        [
            'Search' => 'form'
        ]
    );

    \TYPO3\CMS\Extbase\Utility\ExtensionUtility::configurePlugin(
        'WapplerSystems.meilisearch',
        'pi_frequentlySearched',
        [
            'Search' => 'frequentlySearched'
        ],
        [
            'Search' => 'frequentlySearched'
        ]
    );

    \TYPO3\CMS\Extbase\Utility\ExtensionUtility::configurePlugin(
        'WapplerSystems.meilisearch',
        'pi_suggest',
        [
            'Suggest' => 'suggest'
        ],
        [
            'Suggest' => 'suggest'
        ]
    );

    // add tsconfig
    \TYPO3\CMS\Core\Utility\ExtensionManagementUtility::addPageTSConfig('@import \'EXT:meilisearch/Configuration/TSconfig/Page/Mod/Wizards/NewContentElement.tsconfig\'');

    // register the Fluid namespace 'meilisearch' globally
    $GLOBALS['TYPO3_CONF_VARS']['SYS']['fluid']['namespaces']['meilisearch'] = ['WapplerSystems\\Meilisearch\\ViewHelpers'];
})();

$isComposerMode = defined('TYPO3_COMPOSER_MODE') && TYPO3_COMPOSER_MODE;
if (!$isComposerMode) {
    // we load the autoloader for our libraries
    $dir = \TYPO3\CMS\Core\Utility\ExtensionManagementUtility::extPath('meilisearch');
    require $dir . '/Resources/Private/Php/ComposerLibraries/vendor/autoload.php';
}
