<?php

namespace idoit\Module\SyneticsJdisc\View;

use idoit\Component\FeatureManager\FeatureManager;
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 Symfony\Component\HttpFoundation\Response;

class DiscoveryServerList extends AbstractView
{
    /**
     * @var JDiscServerDao
     */
    private JDiscServerDao $dao;

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

    /**
     * @return array
     */
    private function getListHeaders(): array
    {
        $headers = $this->dao->getHeaders(isys_jdisc_dao::C__CONFIGURATION);
        $headers['discoveryActive'] = 'LC__JDISC__DISCOVERY_SERVER__DISCOVERY_SETTINGS_ACTIVE';
        $filterHeaders = [
            'isys_jdisc_db__id',
            'isys_jdisc_db__title',
            'isys_jdisc_db__host',
            'isys_jdisc_db__database',
            'discoveryActive',
        ];

        return array_filter($headers, fn ($key) => in_array($key, $filterHeaders), ARRAY_FILTER_USE_KEY);
    }

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

    /**
     * @return Response
     * @throws \isys_exception_database
     */
    public function render(): Response
    {
        if ($this->getMode() === C__NAVMODE__PURGE && is_array($_POST[C__GET__ID])) {
            $this->dao->delete($_POST[C__GET__ID]);
            isys_notify::success($this->language->get('LC__JDISC__DISCOVERY_SERVERS__DELETED'));
        }

        if ($this->getMode() === C__NAVMODE__DUPLICATE) {
            foreach ($_POST[C__GET__ID] as $id) {
                $data = $this->dao->getConfiguration((int)$id);
                $data['title'] = $_POST["C__SERVER__{$id}"];
                unset($data['id']);
                $this->dao->save(null, $data);
            }
            isys_notify::success($this->language->get('LC__JDISC__DISCOVERY_SERVER__DUPLICATED'));
        }

        $this->loadServerList();

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

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

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

        $editRight = isys_auth_system::instance()
            ->is_allowed_to(isys_auth::EDIT, 'JDISC/' . C__MODULE__JDISC . '9');
        $deleteRight = isys_auth_system::instance()
            ->is_allowed_to(isys_auth::DELETE, 'JDISC/' . C__MODULE__JDISC . '9');

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

        isys_component_template_navbar::getInstance()
            ->set_js_function(" onclick=\"window.openDuplicateModal('{$url}')\"", C__NAVBAR_BUTTON__DUPLICATE)
//            ->set_js_function(" onclick=\"get_popup('duplicate_jdisc_profile', null, '640', '320');\"", C__NAVBAR_BUTTON__DUPLICATE)
            ->set_active($editRight, C__NAVBAR_BUTTON__DUPLICATE)
            ->set_active($editRight, C__NAVBAR_BUTTON__EDIT)
            ->set_js_onclick($onClick, C__NAVBAR_BUTTON__EDIT)
            ->set_visible(true, C__NAVBAR_BUTTON__EDIT)
            ->set_active($editRight, C__NAVBAR_BUTTON__NEW)
            ->set_visible(true, C__NAVBAR_BUTTON__NEW)
            ->set_active($deleteRight, C__NAVBAR_BUTTON__PURGE)
            ->set_js_onclick($onClick, C__NAVBAR_BUTTON__PURGE)
            ->set_visible(true, 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__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
            ]);

        $list = new isys_component_list(null, $this->dao->getServerList());
        $list->config($this->getListHeaders(), isys_helper_link::get_base() . 'jdisc/discovery-server/[{isys_jdisc_db__id}]', '[{isys_jdisc_db__id}]', true, true);
        $list->set_row_modifier($this, 'modifyRow');
        $list->createTempTable();

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

    /**
     * @param array $row
     *
     * @return void
     * @throws \Exception
     */
    public function modifyRow(array &$row)
    {
        $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['discoveryActive'] = $this->dao->isDiscoverySettingsActive($row['isys_jdisc_db__id']) ? $yes : $no;
    }
}
