<?php
namespace WapplerSystems\Meilisearch\Report;

/***************************************************************
 *  Copyright notice
 *
 *  (c) 2011-2015 Stefan Sprenger <stefan.sprenger@dkd.de>
 *  (c) 2012-2015 Ingo Renner <ingo@typo3.org>
 *  All rights reserved
 *
 *  This script is part of the TYPO3 project. The TYPO3 project is
 *  free software; you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation; either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  The GNU General Public License can be found at
 *  http://www.gnu.org/copyleft/gpl.html.
 *
 *  This script 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 General Public License for more details.
 *
 *  This copyright notice MUST APPEAR in all copies of the script!
 ***************************************************************/

use WapplerSystems\Meilisearch\ConnectionManager;
use WapplerSystems\Meilisearch\System\Meilisearch\MeilisearchConnection;
use TYPO3\CMS\Core\Utility\GeneralUtility;
use TYPO3\CMS\Reports\Status;

/**
 * Provides a status report about whether the installed Meilisearch version matches
 * the required version.
 *
 * @author Stefan Sprenger <stefan.sprenger@dkd.de>
 */
class MeilisearchVersionStatus extends AbstractMeilisearchStatus
{

    /**
     * Required Meilisearch version. The version that gets installed when using the
     * provided install script EXT:meilisearch/Resources/Private/Install/install-meilisearch.sh
     *
     * @var string
     */
    const REQUIRED_SOLR_VERSION = '8.8.1';

    /**
     * Compiles a version check against each configured Meilisearch server.
     *
     */
    public function getStatus()
    {
        $reports = [];
        $meilisearchConnections = GeneralUtility::makeInstance(ConnectionManager::class)->getAllConnections();

        foreach ($meilisearchConnections as $meilisearchConnection) {
            $coreAdmin = $meilisearchConnection->getAdminService();
            /** @var $meilisearchConnection MeilisearchConnection */
            if (!$coreAdmin->ping()) {
                $url = $coreAdmin->__toString();
                $pingFailedMsg = 'Could not ping meilisearch server, can not check version ' . (string)$url;
                $status = GeneralUtility::makeInstance(
                    Status::class,
                    /** @scrutinizer ignore-type */ 'Meilisearch Version',
                    /** @scrutinizer ignore-type */ 'Not accessible',
                    /** @scrutinizer ignore-type */ $pingFailedMsg,
                    /** @scrutinizer ignore-type */ Status::ERROR
                );
                $reports[] = $status;
                continue;
            }

            $meilisearchVersion = $coreAdmin->getMeilisearchServerVersion();
            $isOutdatedVersion = version_compare($this->getCleanMeilisearchVersion($meilisearchVersion), self::REQUIRED_SOLR_VERSION, '<');

            if (!$isOutdatedVersion) {
                continue;
            }

            $formattedVersion = $this->formatMeilisearchVersion($meilisearchVersion);
            $variables = ['requiredVersion' => self::REQUIRED_SOLR_VERSION, 'currentVersion' => $formattedVersion, 'meilisearch' => $coreAdmin];
            $report = $this->getRenderedReport('MeilisearchVersionStatus.html', $variables);
            $status = GeneralUtility::makeInstance(
                Status::class,
                /** @scrutinizer ignore-type */ 'Meilisearch Version',
                /** @scrutinizer ignore-type */ 'Outdated, Unsupported',
                /** @scrutinizer ignore-type */ $report,
                /** @scrutinizer ignore-type */ Status::ERROR
            );

            $reports[] = $status;
        }

        return $reports;
    }

    /**
     * Gets the clean Meilisearch version in case of a custom build which may have
     * additional information in the version string.
     *
     * @param string $meilisearchVersion Unformatted Meilisearch version number as provided by Meilisearch.
     * @return string Clean Meilisearch version number: mayor.minor.patchlevel
     */
    protected function getCleanMeilisearchVersion($meilisearchVersion)
    {
        $explodedMeilisearchVersion = explode('.', $meilisearchVersion);

        $shortMeilisearchVersion = $explodedMeilisearchVersion[0]
            . '.' . $explodedMeilisearchVersion[1]
            . '.' . $explodedMeilisearchVersion[2];

        return $shortMeilisearchVersion;
    }

    /**
     * Formats the Meilisearch server version number. By default this is going
     * to be the simple major.minor.patch-level version. Custom Builds provide
     * more information though, in case of custom builds, their complete
     * version will be added, too.
     *
     * @param string $meilisearchVersion Unformatted Meilisearch version number as provided by Meilisearch.
     * @return string formatted short version number, in case of custom builds followed by the complete version number
     */
    protected function formatMeilisearchVersion($meilisearchVersion)
    {
        $shortMeilisearchVersion = $this->getCleanMeilisearchVersion($meilisearchVersion);
        $formattedMeilisearchVersion = $shortMeilisearchVersion;

        if ($meilisearchVersion != $shortMeilisearchVersion) {
            $formattedMeilisearchVersion .= ' (' . $meilisearchVersion . ')';
        }

        return $formattedMeilisearchVersion;
    }
}
