<?php

namespace App\Concerns;

use Stichoza\GoogleTranslate\Exceptions\LargeTextException;
use Stichoza\GoogleTranslate\Exceptions\RateLimitException;
use Stichoza\GoogleTranslate\Exceptions\TranslationRequestException;
use Stichoza\GoogleTranslate\GoogleTranslate;

trait TranslatorConcern
{
    /**
     * Try to detect and translate text
     *
     * @param string $text
     * @param string $targetLanguage
     * @return array|null
     */
    public function tryToDetectLanguage(string $text, string $targetLanguage): ?array
    {
        $result = null;
        $translator = new GoogleTranslate($targetLanguage, null);

        try {
            $translation = $translator->translate($text);
            $result = [
                'translation' => $translation,
                'language' => $translator->getLastDetectedSource()
            ];
        } catch (LargeTextException|RateLimitException|TranslationRequestException $e) {}

        return $result;
    }
}
