<?php

namespace idoit\Module\Qrcode\Component;

use isys_application;
use isys_cmdb_dao_category_g_access;
use isys_helper_link;
use isys_tenantsettings;

class QrCode
{
    public function getData(int $objectId): array
    {
        $dao = isys_cmdb_dao_category_g_access::instance(isys_application::instance()->container->get('database'));

        $objectData = $dao->get_object_by_id($objectId)
            ->get_row();
        $configuration = isys_tenantsettings::get('qrcode.config', [
            'obj-type' => [],
            'global'   => []
        ]);

        $return = [
            'link'        => $configuration['global']['link'] ?: C__QRCODE__LINK__PRINT,
            'type'        => $configuration['global']['type'] ?: C__QRCODE__TYPE__ACCESS_URL,
            'url'         => $configuration['global']['url'] ?: false,
            'description' => $configuration['global']['description'] ?: false,
            'logo'        => false,
            'sysid'       => $objectData['isys_obj__sysid']
        ];

        // If we find a object-type specific configuration, we use it.
        if (isset($configuration['obj-type'][$objectData['isys_obj_type__const']])) {
            $objectTypeConfiguration = $configuration['obj-type'][$objectData['isys_obj_type__const']];

            // @see ID-1424  If the user deactivated the QR-Code for the given object-type, we simply return an empty array.
            if (!$objectTypeConfiguration['enabled']) {
                return [];
            }

            $return = [
                'link'        => $configuration['global']['link'] ?: C__QRCODE__LINK__PRINT,
                'type'        => $objectTypeConfiguration['type'] ?: C__QRCODE__TYPE__ACCESS_URL,
                'url'         => $objectTypeConfiguration['url'] ?: false,
                'description' => $objectTypeConfiguration['description'] ?: false,
                'logo'        => false,
                'sysid'       => $objectData['isys_obj__sysid']
            ];
        }

        if ($return['type'] == C__QRCODE__TYPE__ACCESS_URL) {
            $return['url'] = $dao->get_url($objectId);
        }

        if ($configuration['global']['logo'] > 0) {
            $return['logo'] = isys_helper_link::create_image_url($configuration['global']['logo']);
        }

        // This will be our "default" QR Code url.
        if (empty($return['url'])) {
            $return['url'] = isys_helper_link::create_url([C__CMDB__GET__OBJECT => $objectId], true);
        }

        // Finally handle the URL variables (also for the description field).
        $return['url'] = (isys_helper_link::handle_url_variables($return['url'], $objectId));
        $return['description'] = isys_helper_link::handle_url_variables($return['description'], $objectId);
        // Clean up the SYSID, because barcodes can only handle certain chars.
        $return['sysid'] = preg_replace('/^.*?[_-]+(.*?)$/', "\\1", $return['sysid']);

        return $return;
    }
}
