<?php

use Yandex\Translate\Translator;
use Yandex\Translate\Exception;

class PolylangTranslatorYandex 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_yandex_key', $config, '', true);
        if ($key) {
            $this->translator = new Translator($key);
        } else {
            $this->modx->log(modX::LOG_LEVEL_ERROR, 'Not set yandex 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);
                $html = $this->modx->getOption('html', $options, true, true);
                $text = $this->beforeTranslation($text);

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

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

                    }
                }

                $text = (string)$this->translator->translate($text, "{$from}-{$to}", $html);
                $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 ($this->translator) {
            if ($lang = $this->translator->detect($text)) {
                return $lang;
            }
        }
        $this->modx->log(modX::LOG_LEVEL_ERROR, 'Error detect language for text:' . $text);
        return false;


    }

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