<?php

namespace Lokalize\Controller;

use App\Controller\App;

class Utils extends App {

    /**
     * Get text translations via deepl
     */
    public function translate() {

        $this->helper('session')->close();
        $this->hasValidCsrfToken(true);

        $text = $this->param('text');
        $to = $this->param('to');
        $context = $this->param('context');

        if (!$text || !$to) {
            return false;
        }

        $translation = $this->module('lokalize')->translate($text, $to, $context);

        if (!$translation) {
            $translation = '';
        }

        return \compact('translation');

    }

    public function translateBatch() {

        $this->helper('session')->close();
        $this->hasValidCsrfToken(true);

        $items = $this->param('items');
        $to = $this->param('to');

        if (!$items || !$to) {
            return false;
        }

        \set_time_limit(0);

        $translations = [];

        foreach ($items as $i => $item) {

            $text = $item['text'] ?? '';
            $context = $item['context'] ?? null;

             if ($text) {
                $translations[$i] = $this->module('lokalize')->translate($text, $to, $context);
             } else {
                $translations[$i] = '';
             }
        }

        return ['translations' => $translations];
    }
}
