<?php

use Panda\Yandex\TranslateSdk;

class PolylangTranslatorYandexCloud extends PolylangTranslatorHandler
{
    /** @var TranslateSdk\Cloud|null $cloud */
    public $cloud = null;

    public function __construct(Polylang &$polylang, $config = array())
    {
        parent::__construct($polylang, $config);
        $key = $this->modx->getOption('polylang_translate_yandex_cloud_key', $config, '', true);
        if ($key) {
            try {
                $this->cloud = TranslateSdk\Cloud::createApi($key);
            } catch (TranslateSdk\Exception\ClientException $e) {
                $this->modx->log(modX::LOG_LEVEL_ERROR, $e->getMessage());
            }
        } else {
            $this->modx->log(modX::LOG_LEVEL_ERROR, 'Not set yandex cloud 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->cloud) return false;
        if ($text) {
            $to = $this->prepareLanguageCode($to);
            $from = $this->prepareLanguageCode($from);
            $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}");
                    }
                }
            }

            try {
                $translate = new TranslateSdk\Translate();
                $translate
                    ->setSourceLang($from)
                    ->setTargetLang($to)
                    ->setFormat(TranslateSdk\Format::HTML)
                    ->addText($text);
                $result = $this->modx->fromJSON($this->cloud->request($translate));
                if (
                    !empty($result) &&
                    isset($result['translations']) &&
                    isset($result['translations'][0])
                ) {
                    $text = $this->afterTranslation($result['translations'][0]['text']);
                }
            } catch (TranslateSdk\Exception\ClientException $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->cloud) {
            try {
                $detect = new TranslateSdk\Detect($text);
                $lang = $this->cloud->request($detect);
                if ($lang && !empty($lang['language'])) {
                    return $lang['language'];
                }
            } catch (TranslateSdk\Exception\ClientException $e) {
                $this->modx->log(modX::LOG_LEVEL_ERROR, 'Error detect language for text:' . $text . 'Info:' . $e->getMessage());
            }
        }
        return false;


    }

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