<?php
namespace WapplerSystems\Meilisearch\System\Meilisearch\Service;

/***************************************************************
 *  Copyright notice
 *
 *  (c) 2009-2017 Timo Hund <timo.hund@dkd.de>
 *  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 MeiliSearch\Client;
use WapplerSystems\Meilisearch\System\Configuration\TypoScriptConfiguration;
use WapplerSystems\Meilisearch\System\Logging\MeilisearchLogManager;
use WapplerSystems\Meilisearch\System\Meilisearch\MeilisearchConnection;
use WapplerSystems\Meilisearch\System\Meilisearch\Parser\SchemaParser;
use WapplerSystems\Meilisearch\System\Meilisearch\Parser\StopWordParser;
use WapplerSystems\Meilisearch\System\Meilisearch\Parser\SynonymParser;
use WapplerSystems\Meilisearch\System\Meilisearch\ResponseAdapter;
use WapplerSystems\Meilisearch\System\Meilisearch\Schema\Schema;
use TYPO3\CMS\Core\Utility\GeneralUtility;

/**
 * Class MeilisearchAdminService
 */
class MeilisearchAdminService extends AbstractMeilisearchService
{

    protected $systemData = null;

    /**
     * @var SchemaParser
     */
    protected $schemaParser = null;

    /**
     * @var Schema
     */
    protected $schema;

    /**
     * @var string
     */
    protected $_synonymsUrl;
    /**
     * @var string
     */
    protected $_stopWordsUrl;

    /**
     * @var SynonymParser
     */
    protected $synonymParser = null;

    /**
     * @var StopWordParser
     */
    protected $stopWordParser = null;

    /**
     * Constructor
     *
     * @param MeilisearchConnection $meilisearchConnection
     * @param Client $client
     * @param TypoScriptConfiguration|null $typoScriptConfiguration
     * @param MeilisearchLogManager|null $logManager
     * @param SynonymParser|null $synonymParser
     * @param StopWordParser|null $stopWordParser
     * @param SchemaParser|null $schemaParser
     */
    public function __construct(
        MeilisearchConnection $meilisearchConnection,
        Client $client,
        TypoScriptConfiguration $typoScriptConfiguration = null,
        MeilisearchLogManager $logManager = null,
        SynonymParser $synonymParser = null,
        StopWordParser $stopWordParser = null,
        SchemaParser $schemaParser = null
    )
    {
        parent::__construct($meilisearchConnection, $client, $typoScriptConfiguration);

        $this->synonymParser = $synonymParser ?? GeneralUtility::makeInstance(SynonymParser::class);
        $this->stopWordParser = $stopWordParser ?? GeneralUtility::makeInstance(StopWordParser::class);
        $this->schemaParser = $schemaParser ?? GeneralUtility::makeInstance(SchemaParser::class);
    }


    /**
     * Gets information about the Meilisearch server
     *
     * @return ResponseAdapter
     */
    public function getSystemInformation()
    {
        if (empty($this->systemData)) {
            $systemInformation = $this->system();

            // access a random property to trigger response parsing
            $this->systemData = $systemInformation;
        }

        return $this->systemData;
    }



    /**
     * Get currently configured synonyms
     *
     * @param string $baseWord If given a base word, retrieves the synonyms for that word only
     * @return array
     */
    public function getSynonyms($baseWord = '')
    {
        $this->initializeSynonymsUrl();
        $synonymsUrl = $this->_synonymsUrl;
        if (!empty($baseWord)) {
            $synonymsUrl .= '/' . $baseWord;
        }

        $response = $this->_sendRawGet($synonymsUrl);
        return $this->synonymParser->parseJson($baseWord, $response->getRawResponse());
    }

    /**
     * Add list of synonyms for base word to managed synonyms map
     *
     * @param string $baseWord
     * @param array $synonyms
     *
     * @return ResponseAdapter
     *
     * @throws \InvalidArgumentException If $baseWord or $synonyms are empty
     */
    public function addSynonym($baseWord, array $synonyms)
    {
        $this->initializeSynonymsUrl();
        $json = $this->synonymParser->toJson($baseWord, $synonyms);
        return $this->_sendRawPost($this->_synonymsUrl, $json, 'application/json');
    }

    /**
     * Remove a synonym from the synonyms map
     *
     * @param string $baseWord
     * @return ResponseAdapter
     * @throws \InvalidArgumentException
     */
    public function deleteSynonym($baseWord)
    {
        $this->initializeSynonymsUrl();
        if (empty($baseWord)) {
            throw new \InvalidArgumentException('Must provide base word.');
        }

        return $this->_sendRawDelete($this->_synonymsUrl . '/' . urlencode($baseWord));
    }

    /**
     * Get currently configured stop words
     *
     * @return array
     */
    public function getStopWords()
    {
        $this->initializeStopWordsUrl();
        $response = $this->_sendRawGet($this->_stopWordsUrl);
        return $this->stopWordParser->parseJson($response->getRawResponse());
    }

    /**
     * Adds stop words to the managed stop word list
     *
     * @param array|string $stopWords string for a single word, array for multiple words
     * @return ResponseAdapter
     * @throws \InvalidArgumentException If $stopWords is empty
     */
    public function addStopWords($stopWords)
    {
        $this->initializeStopWordsUrl();
        $json = $this->stopWordParser->toJson($stopWords);
        return $this->_sendRawPost($this->_stopWordsUrl, $json, 'application/json');
    }

    /**
     * Deletes a words from the managed stop word list
     *
     * @param string $stopWord stop word to delete
     * @return ResponseAdapter
     * @throws \InvalidArgumentException If $stopWords is empty
     */
    public function deleteStopWord($stopWord)
    {
        $this->initializeStopWordsUrl();
        if (empty($stopWord)) {
            throw new \InvalidArgumentException('Must provide stop word.');
        }

        return $this->_sendRawDelete($this->_stopWordsUrl . '/' . urlencode($stopWord));
    }

    /**
     * @return void
     */
    protected function initializeSynonymsUrl()
    {
        if (trim($this->_synonymsUrl) !== '') {
            return;
        }
        $this->_synonymsUrl = $this->_constructUrl(self::SYNONYMS_SERVLET) . $this->getSchema()->getLanguage();
    }

    /**
     * @return void
     */
    protected function initializeStopWordsUrl()
    {
        if (trim($this->_stopWordsUrl) !== '') {
            return;
        }

        $this->_stopWordsUrl = $this->_constructUrl(self::STOPWORDS_SERVLET) . $this->getSchema()->getLanguage();
    }
}
