<?php
/**
 * i-doit PRO
 *
 * Module initializer
 *
 * @package     i-doit
 * @subpackage  Modules
 * @copyright   synetics GmbH
 * @license     http://www.i-doit.com/license
 */

use idoit\Component\Autoloader;
use idoit\Component\Upload\Types\ObjectTypeIcon;
use idoit\Component\Upload\UploadType;
use idoit\Module\Pro\Model\Language;
use idoit\Module\Pro\Upload\CustomTranslationType;
use idoit\Psr4AutoloaderClass;
use Symfony\Component\Config\FileLocator;
use Symfony\Component\Routing\Loader\PhpFileLoader;

if (!defined('C__MODULE__PRO')) {
    define('C__MODULE__PRO', true);
}

// PRO Initialization.
define('C__ENABLE__LICENCE', true);

// URL, where idoit searches for the update XML document.
define('C__IDOIT_UPDATES_PRO', 'https://www.i-doit.com/updates.xml');
define('C__URL__PRO', 'https://portal.i-doit.com');

// Additional main-menu constants.
define('C__MAINMENU__MYDOIT', 1);
define('C__MAINMENU__CMDB_EXPLORER', 2);

// View.
define('C__CMDB__VIEW__TREE_EXPLORER', 1010);
define('C__CMDB__VIEW__EXPLORER', 1101);

// CMDB Explorer views.
define('C__CMDB__VISUALIZATION_VIEW', 'view');
define('C__CMDB__VISUALIZATION_VIEW__OBJECT', 'object');
define('C__CMDB__VISUALIZATION_VIEW__IT_SERVICE', 'it-service');

// CMDB Explorer visualization types.
define('C__CMDB__VISUALIZATION_TYPE', 'type');
define('C__CMDB__VISUALIZATION_TYPE__TREE', 'tree');
define('C__CMDB__VISUALIZATION_TYPE__GRAPH', 'graph');

define('C__VISUALIZATION_PROFILE__OBJ_ID', 'obj-id');
define('C__VISUALIZATION_PROFILE__OBJ_SYS_ID', 'obj-sys-id');
define('C__VISUALIZATION_PROFILE__OBJ_TITLE', 'obj-title');
define('C__VISUALIZATION_PROFILE__OBJ_TITLE_CMDB_STATUS', 'obj-title-cmdb-status');
define('C__VISUALIZATION_PROFILE__OBJ_TYPE_TITLE', 'obj-type-title');
define('C__VISUALIZATION_PROFILE__OBJ_TYPE_TITLE_ICON', 'obj-type-title-icon');
define('C__VISUALIZATION_PROFILE__OBJ_TITLE_TYPE_TITLE_ICON_CMDB_STATUS', 'obj-title-type-title-icon-cmdb-status');
define('C__VISUALIZATION_PROFILE__CMDB_STATUS', 'cmdb-status');
define('C__VISUALIZATION_PROFILE__CATEGORY', 'category');
define('C__VISUALIZATION_PROFILE__PURPOSE', 'purpose');
define('C__VISUALIZATION_PROFILE__PRIMARY_CONTACT', 'primary-contact');
define('C__VISUALIZATION_PROFILE__PRIMARY_ACCESS_URL', 'primary-access-url');
define('C__VISUALIZATION_PROFILE__PRIMARY_IP', 'primary-ip');
define('C__VISUALIZATION_PROFILE__PRIMARY_HOSTNAME', 'primary-hostname');
define('C__VISUALIZATION_PROFILE__PRIMARY_HOSTNAME_FQDN', 'primary-hostname-fqdn');
define('C__VISUALIZATION_PROFILE__RELATION_TYPE', 'relation-type');

// Change product type.
global $g_product_info;

$g_product_info['type'] = 'PRO';

if (class_exists(Autoloader::class) && file_exists(__DIR__ . '/classmap.php')) {
    Autoloader::appendClassmap(require __DIR__ . '/classmap.php');
}

if (class_exists(Psr4AutoloaderClass::class)) {
    Psr4AutoloaderClass::factory()->addNamespace('idoit\Module\Pro', __DIR__ . '/src/');
}

if (isys_application::instance()->container->isCompiled()) {
    // Register some routes.
    isys_application::instance()->container->get('routes')
        ->addCollection((new PhpFileLoader(new FileLocator(__DIR__)))->load('config/routes.php'));

    /**
     * Possible signals
     * - 'mod.settings.extendTree.data-view'
     * - 'mod.settings.extendTree.data-import'
     * - 'mod.settings.extendTree.interfaces'
     *
     * They will always get as first parameter the isys_component_tree component and as second parameter the parent id
     */
    isys_application::instance()->container->get('signals')
        ->connect('mod.settings.extendTree.data-view', ['isys_module_pro', 'extendDataViewTree']);

    $languages = Language::instance(isys_application::instance()->container->get('database_system'))->getAll();
    $availableLanguages = [];

    while ($result = $languages->get_row()) {
        if ($result['available']) {
            $availableLanguages[$result['short']] = $result['title'];
        }
    }

    isys_tenantsettings::extend([
        'LC__UNIVERSAL__CMDB'   => [
            'cmdb.gui.remember-cmdb-status' => [
                'title'   => 'LC__MYDOIT__SAVE_CMDB_STATUS',
                'type'    => 'select',
                'options' => [
                    '0' => 'LC__UNIVERSAL__NO',
                    '1' => 'LC__UNIVERSAL__YES'
                ],
                'default' => '0'
            ]
        ],
        'LC__LANGUAGE_LANGUAGE' => [
            'system.default-language' => [
                'title'   => 'LC__LANGUAGE_DEFAULT_LANGUAGE',
                'type'    => 'select',
                'options' => $availableLanguages,
                'default' => 'en'
            ]
        ],
    ]);

    // @see ID-9997 Only process this logic, if the user is logged in.
    if (isys_application::instance()->container->get('session')->is_logged_in()) {
        isys_component_signalcollection::get_instance()
            ->connect('system.gui.beforeRender', function () {
                if ((int)isys_application::instance()->container->get('settingsUser')->get('pro.news.download-center', 0) === 0
                    && isys_auth_system::instance()->is_allowed_to(isys_auth::EXECUTE, 'DOWNLOADER')
                ) {
                    isys_application::instance()->container->get('template')
                        ->appendInlineJavascript("Modal.openLegacy({
                        popupType:  'download_center_info',
                        maxWidth:      533,
                        maxHeight:     430
                    });");
                }
            });
    }
}

isys_request_controller::instance()
    ->addModuleRoute('GET', '/pro/translation/get-custom', 'pro', 'Translation', 'getTranslations')
    ->addModuleRoute('POST', '/pro/translation/save-custom', 'pro', 'Translation', 'saveTranslations')
    ->addModuleRoute('POST', '/pro/translation/create-custom-translation', 'pro', 'Translation', 'createNewTranslation');

// Create new upload types for custom translations.
isys_application::instance()->container->get('upload')
    ->registerUploadType('pro.translation-flag-icon', (new UploadType())
        ->setUploadDirectory('/images/languages/')
        ->setValidExtensions(['jpeg', 'jpg', 'png', 'gif', 'bmp'])
        ->setSizeLimit(1048576) // 1 MB
        ->setCallbackAfterUpload([ObjectTypeIcon::class, 'processUpload'])) // Will resize the uploaded image to 16x16
    ->registerUploadType('pro.translation-import', (new UploadType())
        ->setUploadDirectory('/temp/')
        ->setValidExtensions(['json'])
        ->setSizeLimit(16777216) // 16 MB
        ->setCallbackAfterUpload([CustomTranslationType::class, 'processUpload']));
