<?php

namespace idoit\Module\SyneticsJdisc\View;

use idoit\Component\FeatureManager\FeatureManager;
use idoit\Component\Helper\Unserialize;
use idoit\Module\SyneticsJdisc\Model\JDiscProfileDao;
use idoit\Module\SyneticsJdisc\Model\JDiscServerDao;
use isys_application;
use isys_auth;
use isys_auth_system;
use isys_component_list;
use isys_component_template_navbar;
use isys_helper_link;
use isys_jdisc_dao;
use isys_module_synetics_jdisc;
use isys_notify;
use isys_tenantsettings;
use Symfony\Component\HttpFoundation\Response;

class SyncProfileList extends AbstractView
{
    /**
     * @var JDiscProfileDao
     */
    private JDiscProfileDao $dao;

    private JDiscServerDao $serverDao;

    /**
     * @throws \Exception
     */
    public function __construct()
    {
        parent::__construct();
        $this->dao = JDiscProfileDao::instance(isys_application::instance()->container->get('database'));
        $this->serverDao = JDiscServerDao::instance(isys_application::instance()->container->get('database'));
    }

    /**
     * @return array
     */
    private function getListHeaders(): array
    {
        $headers = $this->dao->getHeaders(isys_jdisc_dao::C__PROFILES);
        $filterHeaders = [
            'isys_jdisc_profile__id',
            'isys_jdisc_profile__jdisc_server',
            'isys_jdisc_profile__title',
        ];

        $headers = array_filter($headers, fn ($key) => in_array($key, $filterHeaders), ARRAY_FILTER_USE_KEY);
        $headers['last_sync'] = $this->language->get('LC__JDISC__SYNC_PROFILES__LAST_SYNC');
        return $headers;
    }

    /**
     * @return static
     * @throws \Exception
     */
    public static function factory(): static
    {
        $instance = new static();
        $instance->template->assign('content_title', $instance->language->get('LC__JDISC__TREE__SYNC_PROFILES'));
        return $instance;
    }

    /**
     * @return Response
     * @throws \Exception
     */
    public function render(): Response
    {
        if (!empty($_POST[C__GET__ID]) && is_array($_POST[C__GET__ID])) {
            if ($this->getMode() === C__NAVMODE__PURGE) {
                $this->dao->delete($_POST[C__GET__ID]);
            }

            if ($this->getMode() === C__NAVMODE__DUPLICATE) {
                foreach ($_POST[C__GET__ID] as $id) {
                    $data = $this->dao->getProfile((int)$id);
                    $data['title'] = $_POST["C__PROFILE__{$id}"];
                    array_walk($data[isys_jdisc_dao::C__OBJECT_TYPE_ASSIGNMENTS], function (&$value) {
                        unset($value['id']);
                    });
                    $this->dao->save(null, $data);
                }
                isys_notify::success($this->language->get('LC__JDISC__SYNC_PROFILES__DUPLICATED'));
            }
        }

        $this->loadProfiles();

        return self::getResponse()
            ->setTemplate('contentbottomcontent', isys_module_synetics_jdisc::getPath() . 'templates/sync-profile-list.tpl');
    }

    /**
     * @return void
     * @throws \isys_exception_database
     */
    private function loadProfiles(): void
    {
        if (!defined('C__MODULE__JDISC') ||
            !defined('C__MODULE__IMPORT') ||
            !FeatureManager::isFeatureActive('jdisc-settings')
        ) {
            return;
        }

        $resultSet = $this->dao->getProfileList();
        $properties = $this->dao->getProperties();

        $list = new isys_component_list(null, $this->dao->getProfileList());
        $list->config($this->getListHeaders(), isys_helper_link::get_base() . 'jdisc/sync-profile/[{isys_jdisc_profile__id}]', '[{isys_jdisc_profile__id}]', true, true);
        $list->set_row_modifier($this, 'modifyRow');
        $list->createTempTable();

        $onClick = "document.isys_form.sort.value=''; document.isys_form.navMode.value=this.getAttribute('data-navmode'); $('isys_form').submit();";

        $this->template->smarty_tom_add_rule("tom.content.navbar.cRecStatus.p_bInvisible=1")
            ->assign('profiles', $list->getTempTableHtml());

        $l_edit_right = isys_auth_system::instance()
            ->is_allowed_to(isys_auth::EDIT, 'JDISC/' . C__MODULE__JDISC . '10');

        $url = isys_application::instance()->container->get('route_generator')->generate('jdisc.sync-profile.popup.duplicate');

        isys_component_template_navbar::getInstance()
            ->set_js_function(" onclick=\"window.openDuplicateModal('{$url}')\"", C__NAVBAR_BUTTON__DUPLICATE)
            ->set_active($l_edit_right, C__NAVBAR_BUTTON__DUPLICATE)
            ->set_active($l_edit_right, C__NAVBAR_BUTTON__NEW)
            ->set_active($l_edit_right, C__NAVBAR_BUTTON__EDIT)
            ->set_js_onclick($onClick, C__NAVBAR_BUTTON__EDIT)
            ->set_visible(true, C__NAVBAR_BUTTON__DUPLICATE)
            ->set_active(isys_auth_system::instance()
                ->is_allowed_to(isys_auth::DELETE, 'JDISC/' . C__MODULE__JDISC . '10'), C__NAVBAR_BUTTON__PURGE)
            ->set_visible(true, C__NAVBAR_BUTTON__PURGE)
            ->set_js_onclick($onClick, C__NAVBAR_BUTTON__PURGE)
            ->set_visible(false, C__NAVBAR_BUTTON__ARCHIVE)
            ->set_visible(false, C__NAVBAR_BUTTON__DELETE)
            ->set_visible(false, C__NAVBAR_BUTTON__RECYCLE)
            ->append_button('LC__UNIVERSAL__EXPORT', 'export', [
                'active'              => true,
                'icon'                => 'axialis/basic/symbol-download.svg',
                'navmode'             => C__NAVMODE__EXPORT,
                'js_onclick'          => $onClick
            ])
            ->append_button('LC__UNIVERSAL__IMPORT', 'import', [
                'active'              => true,
                'icon'                => 'axialis/basic/symbol-upload.svg',
                'navmode'             => C__NAVMODE__IMPORT,
                'js_onclick'         => "window.openImportProfileModal()"
            ])
            ->append_button('LC__MODULE__JDISC__IMPORT', 'to-import-link', [
                'active'              => true,
                'visible'             => true,
                'tooltip'             => null,
                'icon'                => isys_module_synetics_jdisc::getWwwPath() . "assets/jdisc.png",
                'icon_inactive'       => isys_module_synetics_jdisc::getWwwPath() . "assets/jdisc.png",
                'url'                 => '?moduleID=' . C__MODULE__IMPORT . '&param=' . C__IMPORT__GET__JDISC
            ]);
    }

    /**
     * @param array $row
     *
     * @return void
     * @throws \Exception
     */
    public function modifyRow(array &$row)
    {
        // @todo retrieve last sync from the logs
        $row['last_sync'] = isys_tenantsettings::get('gui.empty_value', '-');

        if (isset($row['isys_jdisc_profile__description'])) {
            $row['isys_jdisc_profile__description'] = nl2br($row['isys_jdisc_profile__description']);
        }

        if (isset($row['isys_jdisc_profile__categories'])) {
            $l_supported_categories = $this->dao->getJdiscDao()->get_supported_categories();
            $l_selected_categories = Unserialize::toArray($row['isys_jdisc_profile__categories']);
            $l_formatted_categories = [];
            if (count($l_selected_categories) === 0) {
                $row['isys_jdisc_profile__categories'] = $this->language->get('LC_UNIVERSAL__NONE_SELECTED');
            } else {
                foreach ($l_supported_categories as $l_supported_category) {
                    if (in_array($l_supported_category['id'], $l_selected_categories)) {
                        $l_formatted_categories[] = $l_supported_category['val'];
                    }
                }

                if (count($l_formatted_categories) === 0) {
                    $row['isys_jdisc_profile__categories'] = $this->language->get('LC_UNIVERSAL__NONE_SELECTED');
                } else {
                    $l_string_to_list = function ($p_value) {
                        return '<li>' . $p_value . '</li>';
                    };
                    $l_formatted_categories = array_map($l_string_to_list, $l_formatted_categories);
                    $row['isys_jdisc_profile__categories'] = '<ul>' . implode(PHP_EOL, $l_formatted_categories) . '</ul>';
                }
            }
        }

        $jdiscServersResult = $this->serverDao->getServerList($row['isys_jdisc_profile__jdisc_server'] ?? null);
        $jdiscServers = [];
        while ($jdiscServer = $jdiscServersResult->get_row()) {
            if ($jdiscServer['isys_jdisc_db__default_server']) {
                $jdiscServers = [
                    $jdiscServer
                ];
                break;
            }
            $jdiscServers[] = $jdiscServer;
        }

        $row['isys_jdisc_profile__jdisc_server'] = '';

        if (count($jdiscServers)) {
            $jdiscServerData = array_pop($jdiscServers);

            $row['isys_jdisc_profile__jdisc_server'] = $jdiscServerData['isys_jdisc_db__host'] . ':' . $jdiscServerData['isys_jdisc_db__database'] .
                ($jdiscServerData['isys_jdisc_db__title'] ? ' (' . $jdiscServerData['isys_jdisc_db__title'] . ')' : '');
        }

        $imageDir = isys_application::instance()->www_path . 'images/axialis/basic/';

        $yes = '<div class="display-flex align-items-center">' .
            '<img src="' . $imageDir . 'symbol-ok.svg" class="mr5" />' .
            '<span class="text-green">' . $this->language->get('LC__UNIVERSAL__YES') . '</span>' .
            '</div>';
        $no = '<div class="display-flex align-items-center">' .
            '<img src="' . $imageDir . 'symbol-cancel.svg" class="mr5" />' .
            '<span class="text-red">' . $this->language->get('LC__UNIVERSAL__NO') . '</span>' .
            '</div>';

        $row['isys_jdisc_profile__import_all_software'] = $row['isys_jdisc_profile__import_all_software'] ? $yes : $no;
        $row['isys_jdisc_profile__import_software_licences'] = $row['isys_jdisc_profile__import_software_licences'] ? $yes : $no;
        $row['isys_jdisc_profile__import_software_services'] = $row['isys_jdisc_profile__import_software_services'] ? $yes : $no;
        $row['isys_jdisc_profile__import_all_networks'] = $row['isys_jdisc_profile__import_all_networks'] ? $yes : $no;
        $row['isys_jdisc_profile__import_all_clusters'] = $row['isys_jdisc_profile__import_all_clusters'] ? $yes : $no;
        $row['isys_jdisc_profile__import_all_blade_connections'] = $row['isys_jdisc_profile__import_all_blade_connections'] ? $yes : $no;
        $row['isys_jdisc_profile__import_custom_attributes'] = $row['isys_jdisc_profile__import_custom_attributes'] ? $yes : $no;
        $row['isys_jdisc_profile__use_default_templates'] = $row['isys_jdisc_profile__use_default_templates'] ? $yes : $no;
        $row['isys_jdisc_profile__import_all_vlans'] = $row['isys_jdisc_profile__import_all_vlans'] ? $yes : $no;
    }
}
