<?php
require_once(dirname(__FILE__) . '/clone.class.php');

class PolylangLexiconEntriesTranslateProcessor extends PolylangLexiconEntriesCloneProcessor
{
    public $classKey = 'LexiconEntries';
    public $permission = 'polylang_lexicon_translate';
    /** @var Polylang $polylang */
    public $polylang;
    /** @var PolylangTools $tools */
    public $tools;
    /** @var PolylangTranslatorHandler $translator */
    public $translator = null;

    public function initialize()
    {
        $initialized = parent::initialize();
        if ($initialized) {
            $scriptTimeLimit = $this->modx->getOption('polylang_script_time_limit', null, 180, true);
            $reconnectTimeout = $this->modx->getOption('polylang_reconnect_timeout', null, 800, true);
            @set_time_limit($scriptTimeLimit);
            PolylangTools::setSessionWaitTimeout($this->modx, $reconnectTimeout);
            $this->translator = $this->polylang->getTranslator();
            if (!$this->translator->isInitialized()) {
                $initialized = $this->failure($this->modx->lexicon('polylang_translator_err_initialization'));
            }
        }
        return $initialized;
    }

    public function process()
    {
        $lexicons = array();
        $all = $this->getProperty('all');
        $language = $this->getProperty('language');
        $languages = $this->getProperty('languages');
        $skipExisting = $this->getProperty('skip_existing', false);

        if (!$all) {
            $lexicons = $this->getProperty('lexicons');
            $lexicons = $this->tools->fromJSON($lexicons, array());
            if (empty($lexicons)) {
                return $this->failure();
            }
        }

        $data = $this->tools->getLexicons($language);
        if ($data) {
            foreach ($data as $item) {
                if (
                    empty($item['value']) ||
                    ($lexicons && !in_array($item['name'], $lexicons))
                ) {
                    continue;
                }
                $lexicon = array(
                    'name' => $item['name'],
                    'topic' => $item['topic'],
                    'namespace' => $item['namespace'],
                );
                foreach ($languages as $key => $val) {
                    if (!$val) continue;
                    $lexicon['language'] = $key;
                    $value = $this->translator->translate($item['value'], $language, $key);
                    if ($value) {
                        $this->copy($value, $lexicon, $skipExisting);
                    }

                }
            }
        }
        return $this->success();
    }
}

return 'PolylangLexiconEntriesTranslateProcessor';