<?php

use Google\Cloud\Translate\V2\TranslateClient;

class PolylangTranslatorGoogle extends PolylangTranslatorHandler
{
    /** @var Translator|null $translator */
    public $translator = null;

    public function __construct(Polylang &$polylang, $config = array())
    {
        parent::__construct($polylang, $config);
        $key = $this->modx->getOption('polylang_translate_google_key', $config, '', true);
        $referer = MODX_URL_SCHEME . MODX_HTTP_HOST;
        if ($key) {
            $this->translator = new TranslateClient(array(
                'key' => $key,
                'restOptions' => array(
                    'headers' => array(
                        'referer' => $referer
                    )
                )
            ));
        } else {
            $this->modx->log(modX::LOG_LEVEL_ERROR, 'Not set google API key!');
        }
    }


    /**
     * @param string $text
     * @param string $from
     * @param string $to
     * @param array $options
     *
     * @return string|false
     */
    public function translate(string $text, string $from, string $to, array $options = array())
    {
        if (!$this->translator) return false;
        try {
            if ($text) {
                $from = $this->prepareLanguageCode($from);
                $to = $this->prepareLanguageCode($to);
                $beforeText = $this->beforeTranslation($text);

                if ($this->isDetectSourceLanguage) {
                    if ($detectLang = $this->detectLanguage($beforeText)) {
                        $from = $detectLang;

                        if ($this->tools->debug) {
                            $this->modx->log(modX::LOG_LEVEL_ERROR, "[Translate] Detected source language:{$from}");
                        }

                    }
                }

                $result = $this->translator->translate($beforeText, array('source' => $from, 'target' => $to));
                $text = isset($result['text']) ? $result['text'] : '';
                $text = $this->afterTranslation($text);
            }
        } catch (Exception $e) {
            $this->modx->log(modX::LOG_LEVEL_ERROR, $e->getMessage());
            return false;
        }
        return $text;
    }

    /**
     * @param string $text
     * @return false|string
     */
    public function detectLanguage(string $text)
    {
        if ($result = $this->translator->detectLanguage($text)) {
            return $result['languageCode'];
        }
        $this->modx->log(modX::LOG_LEVEL_ERROR, 'Error detect language for text:' . $text);
        return false;
    }

    /**
     * @return bool
     */
    public function isInitialized()
    {
        return $this->translator !== null;
    }
}
