<?php

namespace idoit\Module\SyneticsJdisc\View;

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_template_navbar;
use isys_jdisc_dao;
use isys_module_synetics_jdisc;
use isys_tenantsettings;

class SyncProfile extends AbstractEntryView
{
    /**
     * @var JDiscProfileDao
     */
    private JDiscProfileDao $dao;

    /**
     * @var JDiscServerDao
     */
    private JDiscServerDao $serverDao;

    public function __construct()
    {
        parent::__construct();
        $this->dao = new JDiscProfileDao();
        $this->serverDao = new JDiscServerDao();
    }

    /**
     * @return string[]
     */
    public static function getImportModes(): array
    {
        return [
            isys_module_synetics_jdisc::C__IMPORT_MODE__CREATE                  => 'LC__MODULE__JDISC__IMPORT__MODE_APPEND',
            isys_module_synetics_jdisc::C__IMPORT_MODE__CREATE_ONLY_NEW_DEVICES => 'LC__MODULE__JDISC__IMPORT__MODE_APPEND_NEW_ONLY',
            isys_module_synetics_jdisc::C__IMPORT_MODE__UPDATE                  => 'LC__MODULE__JDISC__IMPORT__MODE_UPDATE',
            isys_module_synetics_jdisc::C__IMPORT_MODE__UPDATE_NEW_DISCOVERY    => 'LC__MODULE__JDISC__IMPORT__MODE_UPDATE_NEW_DISCOVERED',
            isys_module_synetics_jdisc::C__IMPORT_MODE__UPDATE_EXISTING_ONLY    => 'LC__MODULE__JDISC__IMPORT__MODE_UPDATE_EXISTING_ONLY',
            isys_module_synetics_jdisc::C__IMPORT_MODE__OVERWRITE               => 'LC__MODULE__JDISC__IMPORT__MODE_OVERWRITE',
            isys_module_synetics_jdisc::C__IMPORT_MODE__OVERWRITE_NEW_DISCOVERY => 'LC__MODULE__JDISC__IMPORT__MODE_OVERWRITE_NEW_DISCOVERED',
        ];
    }

    /**
     * @return array
     * @throws \Exception
     */
    public static function getLoggingDialogData(): array
    {
        $language = isys_application::instance()->container->get('language');

        return [
            0 => $language->get("LC__MODULE__JDISC__IMPORT__LOGGING_LESS"),
            1 => $language->get("LC__MODULE__JDISC__IMPORT__LOGGING_DETAIL"),
            2 => $language->get("LC__MODULE__JDISC__IMPORT__LOGGING_DEBUG"),
        ];
    }

    /**
     * @return JDiscProfileDao
     */
    public function getDao(): JDiscProfileDao
    {
        return $this->dao;
    }

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

    /**
     * @return void
     */
    private function loadNavbar(): void
    {
        $navbar = isys_component_template_navbar::getInstance();

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

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

        switch ($this->getMode()) {
            case C__NAVMODE__NEW:
                $navbar
                    ->set_active(true, C__NAVBAR_BUTTON__SAVE)
                    ->set_js_onclick($onClick, C__NAVBAR_BUTTON__SAVE)
                    ->set_active(true, C__NAVBAR_BUTTON__CANCEL)
                    ->set_js_onclick($onClick, C__NAVBAR_BUTTON__CANCEL)
                    ->set_active(false, C__NAVBAR_BUTTON__EDIT)
                    ->set_active(false, C__NAVBAR_BUTTON__NEW);
                break;
            case C__NAVMODE__EDIT:
            default:
                $navbar
                    ->set_visible(true, C__NAVBAR_BUTTON__SAVE)
                    ->set_active(true, C__NAVBAR_BUTTON__SAVE)
                    ->set_js_onclick($onClick, C__NAVBAR_BUTTON__SAVE)
                    ->set_active(true, C__NAVBAR_BUTTON__CANCEL)
                    ->set_js_onclick($onClick, C__NAVBAR_BUTTON__CANCEL)
                    ->set_active(false, C__NAVBAR_BUTTON__EDIT)
                    ->set_active(false, C__NAVBAR_BUTTON__NEW);
                break;
        }

        $navbar->set_active(false, C__NAVBAR_BUTTON__PURGE)
            ->set_visible(false, C__NAVBAR_BUTTON__ARCHIVE)
            ->set_visible(false, C__NAVBAR_BUTTON__DELETE)
            ->set_visible(false, C__NAVBAR_BUTTON__PURGE)
            ->set_visible(false, C__NAVBAR_BUTTON__RECYCLE);
    }

    /**
     * @return void
     */
    private function loadContent(): void
    {
        $properties = $this->dao->getProperties();

        $data = [];
        $data = $this->dao->prepareData();
        $validationErrors = $this->getValidationErrors();

        if ($this->getMode() === C__NAVMODE__SAVE) {
            unset($validationErrors['id']);

            if (!empty(array_filter($validationErrors, fn ($item) => $item > 0))) {
                $this->setMode(C__NAVMODE__EDIT);
                $this->template->activate_editmode();
                $this->render();
                return;
            }
        }

        if ($this->getId() > 0) {
            $data = $this->dao->getProfile($this->getId());
        }
        $jdiscServer = null;

        if (isset($data['jdisc_server'])) {
            $jdiscServer = $data['jdisc_server'];
        }

        $columnSettings = $this->dao->getDefaultColumnSettings();

        if (isset($data['column_settings'])) {
            $columnSettings = $data['column_settings'];
        }

        // Use default jdisc server
        if ($jdiscServer === null) {
            $jdiscServer = $this->serverDao->getServerList(null, ['isys_jdisc_db__default_server = 1'])
                ->get_row_value('isys_jdisc_db__id');
            $data['jdisc_server'] = $jdiscServer;
        }

        if (!empty($data['categories']) && is_string($data['categories'])) {
            // Unserialize categories ($data came directly from database):
            $data['categories'] = Unserialize::toArray($data['categories']);
        }

        $properties['categories'][C__PROPERTY__UI][C__PROPERTY__UI__PARAMS]['p_arData'] = $this->dao->getSelectedCategories($data['categories'] ?? null);

        if (!empty($data['network_adresses']) && is_string($data['network_adresses'])) {
            // Unserialize network_adresses ($data came directly from database):
            $data['network_adresses'] = Unserialize::toArray($data['network_adresses']);
        }

        $properties['network_adresses'][C__PROPERTY__UI][C__PROPERTY__UI__PARAMS]['p_arData'] = $this->dao->getNetworkAddressFilter($data['network_adresses'] ?? null);
        $macCategoriesIds = $this->dao->getMacCategoryIds();
        $macCategoriesSelected = is_array($data['categories']) && array_intersect($data['categories'], $macCategoriesIds);

        $filterTypes = [];
        $filterFiles = [];

        if (is_dir($filterDir = isys_module_synetics_jdisc::getPath() . 'templates/filter/')) {
            $filters = scandir($filterDir);
            foreach ($filters as $filterFile) {
                if ($filterFile === '.' || $filterFile === '..') {
                    continue;
                }

                if (file_exists($filterDir . $filterFile) && is_file($filterDir . $filterFile)) {
                    $filterFiles[] = $filterDir . $filterFile;
                    $filterType = rtrim($filterFile, '.tpl');
                    $filterTypes[$filterType] = 'LC__MODULE__JDISC__IMPORT__FILTER_TYPE__' . strtoupper($filterType);
                }
            }
        }

        $rules = $this->dao->getJdiscModule()->prepare_user_data_assignment($properties, $data, $validationErrors);

        if (count($filterTypes) > 0) {
            $rules['C__MODULE__JDISC__SYNC_CONFIG__FILTER']['p_arData'] = $filterTypes;
            $this->template->assign('filter_files', $filterFiles);
        }
        $groups = [
            '-1' => isys_tenantsettings::get('gui.empty_value', '-'),
        ];

        if ($rules['C__MODULE__JDISC__IMPORT__JDISC_SERVERS']['p_strSelectedID'] > 0) {
            $groups += $this->dao->getJDiscGroups($rules['C__MODULE__JDISC__IMPORT__JDISC_SERVERS']['p_strSelectedID']);

            $rules['C__MODULE__JDISC__SYNC_CONFIG__GROUP']['p_strSelectedID'] = !isset($groups[$data['conf_group_id']]) ? null : $data['conf_group_id'];
        }

        $rules['C__MODULE__JDISC__SYNC_CONFIG__GROUP']['p_arData'] = $groups;
        $rules['C__MODULE__JDISC__SYNC_CONFIG__JDISC_SERVERS'] = $rules['C__MODULE__JDISC__IMPORT__JDISC_SERVERS'];
        $rules['C__MODULE__JDISC__SYNC_CONFIG__JDISC_SERVERS']['p_strSelectedID'] = $data['conf_server_id'];
        $rules['C__MODULE__JDISC__SYNC_CONFIG__MODE']['p_strSelectedID'] = $data['conf_import_mode'];
        $rules['C__MODULE__JDISC__SYNC_CONFIG__LOGGING']['p_strSelectedID'] = $data['conf_logging'];
        $rules['C__MODULE__JDISC__SYNC_CONFIG__IP_CONFLICTS']['p_strSelectedID'] = $data['conf_overwrite_ip'];

        $this->template
            ->activate_editmode()
            ->assign('confSearchIndex', $data['conf_search_index'])
            ->assign('columnSettings', $columnSettings)
            ->assign('editMode', $this->template::editmode())
            ->assign('id', $this->getId() ?? null)
            ->assign('jdisc_ajax_url', "?call=jdisc&ajax=1")
            ->assign('titleTransformation', $this->dao->getTitleTransformation())
            ->assign('is_jedi_version', $this->dao->isJediVersion())
            ->assign('jdisc_types', $this->dao->getJdiscTypes())
            ->assign('update_objtype', (bool)$data['update_objtype'])
            ->assign('update_obj_title', (bool)$data['update_obj_title'])
            ->assign('import_all_software', (bool)$data['import_all_software'])
            ->assign('import_software_licences', (bool)$data['import_software_licences'])
            ->assign('import_software_services', (bool)$data['import_software_services'])
            ->assign('import_cloud_subscriptions', (bool)$data['import_cloud_subscriptions'])
            ->assign('importCreateCloudUsers', (bool)$data['import_create_cloud_users'])
            ->assign('importConnectionEndpoint', (bool)$data['import_connection_endpoint'])
            ->assign('import_all_networks', (bool)$data['import_all_networks'])
            ->assign('import_all_clusters', (bool)$data['import_all_clusters'])
            ->assign('import_all_blade_connections', (bool)$data['import_all_blade_connections'])
            ->assign('import_custom_attributes', (bool)$data['import_custom_attributes'])
            ->assign('use_default_templates', (bool)$data['use_default_templates'])
            ->assign('import_all_vlans', (bool)$data['import_all_vlans'])
            ->assign('jdisc_operating_systems', $this->dao->getJdiscOs())
            ->assign('object_types', $this->dao->getObjectTypes())
            ->assign('matching_profiles', $this->dao->getMatchingProfiles())
            ->assign('object_type_assignments', $data[isys_jdisc_dao::C__OBJECT_TYPE_ASSIGNMENTS])
            ->assign('useSimpleDatabaseModel', (bool)$data['use_simple_database_mod'])
            ->assign('macCategoriesString', implode(',', $macCategoriesIds))
            ->assign('macCategoriesSelected', $macCategoriesSelected)
            ->assign('object_type_assignment_file', isys_module_synetics_jdisc::getPath() . 'templates/' . 'object_type_assignment.tpl')
            ->smarty_tom_add_rules(
                'tom.content.bottom.content',
                $rules
            );
    }

    /**
     * @return \Symfony\Component\HttpFoundation\Response
     * @throws \Exception
     */
    public function render(): \Symfony\Component\HttpFoundation\Response
    {
        $this->loadNavbar();
        $this->loadContent();

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