<?php

class PolylangLexiconEntriesImportProcessor extends modProcessor
{
    public $classKey = 'LexiconEntries';
    public $permission = 'polylang_lexicon_import';
    /** @var Polylang $polylang */
    public $polylang;
    /** @var PolylangTools $tools */
    public $tools;
    /** @var array */
    protected $languages = array();

    public function initialize()
    {
        if (!$this->modx->hasPermission($this->permission)) {
            return $this->modx->lexicon('access_denied');
        }
        $file = $this->getProperty('file');
        if (empty($file) || !isset($file['tmp_name'])) return $this->modx->lexicon('import_err_upload');
        if ($file['error'] != 0) return $this->modx->lexicon('import_err_upload');
        if (!file_exists($file['tmp_name'])) return $this->modx->lexicon('import_err_upload');

        $json = file_get_contents($file['tmp_name']);
        if (empty($json)) return $this->modx->lexicon('import_err_upload');
        $initialized = parent::initialize();
        if ($initialized) {
            $this->polylang = $this->modx->getService('polylang', 'Polylang');
            $this->tools = $this->polylang->getTools();
            $this->languages = $this->tools->fromJSON($json, array());
            $this->setDefaultProperties(array(
                'namespace' => 'polylang',
                'topic' => 'site',
            ));
        }
        return $initialized;
    }

    public function getLanguageTopics()
    {
        return array('polylang:default');
    }

    public function process()
    {
        $onlyMissing = $this->getProperty('only_missing', false);
        foreach ($this->languages as $language => $lexicons) {
            $this->tools->createLexiconFile($language);
            if ($onlyMissing) {
                $currLexicons = $this->tools->getLexicons($language);
            }
            foreach ($lexicons as $lexicon) {
                if (!empty($currLexicons) && $this->inLexicon($lexicon['name'], $currLexicons)) continue;
                $this->addLexicon($lexicon);
            }
        }
        return $this->success();
    }

    /**
     * @param array $lexicon
     *
     * @return bool
     */
    public function addLexicon(array $lexicon)
    {
        /** @var modLexiconEntry $entry */
        $entry = $this->modx->getObject('modLexiconEntry', $lexicon);
        if (empty($entry)) {
            $entry = $this->modx->newObject('modLexiconEntry');
        } else {
            $entry->set('editedon', date('Y-m-d H:i:s'));
            $entry->clearCache();
        }
        $entry->fromArray($lexicon);
        return $entry->save();
    }

    /**
     * @param string $name
     * @param array $lexicons
     *
     * @return bool
     */
    public function inLexicon($name, array $lexicons)
    {
        foreach ($lexicons as $lexicon) {
            if ($lexicon['name'] == $name) return true;
        }
        return false;
    }
}

return 'PolylangLexiconEntriesImportProcessor';