<?php

namespace idoit\Module\Pro\Upload;

use idoit\Module\Pro\Model\Language;
use idoit\Module\Pro\Model\Translation;
use isys_application;
use isys_component_constant_manager;
use isys_format_json as JSON;

/**
 * Class CustomTranslationType
 *
 * @package idoit\Module\Pro\Upload
 */
class CustomTranslationType
{
    /**
     * Method for processing the custom translation import.
     *
     * @param string $filePath
     *
     * @return array
     * @throws \idoit\Exception\JsonException
     * @throws \isys_exception_dao
     * @throws \isys_exception_database
     */
    public static function processUpload(string $filePath)
    {
        $languageModel = Language::instance(isys_application::instance()->container->get('database_system'));
        $log = [];

        // Get request data.
        $request = isys_application::instance()->container->get('request');

        // Read the language data.
        $languageData = JSON::decode(file_get_contents($filePath));
        $log[] = 'Processing language "' . $languageData['short'] . '"';

        // Create icon, if necessary
        if (!empty($languageData['iconPath']) && !empty($languageData['iconContent'])) {
            $log[] = 'Creating icon';
            isys_file_put_contents(BASE_DIR . 'images/' . $languageData['iconPath'], base64_decode($languageData['iconContent']));
        }

        // Check if we need to create or update.
        $existingLanguage = $languageModel->getByAbbreviation($languageData['short']);

        if (isset($existingLanguage['title'])) {
            $log[] = 'Name with same abbreviation already exists, updating...';
            $languageModel->save($languageData['short'], $languageData['title'], (string)$languageData['iconPath'], (bool)$languageData['available']);
        } else {
            $log[] = 'Creating new language...';
            $languageModel->create($languageData['short'], $languageData['title'], (string)$languageData['iconPath'], (bool)$languageData['available']);
        }

        if (count($languageData['custom-translations'])) {
            $log[] = 'Processing translations';

            $merge = $request->query->get('merge', 0);

            $log[] = $merge ? 'Merging them with existing ones' : 'Overwriting existing ones';

            (new Translation())->saveCustomTranslations($languageData['short'], $languageData['custom-translations'], $merge);
        }

        // @see ID-10333 Clear the DCS cache in order to re-create the language constants.
        $log[] = 'Clear constant cache';
        isys_component_constant_manager::instance()->clear_dcs_cache();

        $log[] = 'All done!';

        unlink($filePath);

        return $log;
    }
}
