<?php

namespace idoit\Module\SyneticsJdisc\Model;

use idoit\Module\SyneticsJdisc\Graphql\Connector;
use idoit\Module\SyneticsJdisc\Graphql\Query\DeviceListColumns;
use isys_application;

class DeviceListColumnsDao extends AbstractJDiscDao
{
    // these columns are always visible in the device list
    private array $alwaysVisibleColumns = ['deviceId', 'Name', 'deviceType'];

    /**
     * Returns the columns for the device list.
     *
     * Example:
     * {
     *    "model": {
     *       "name": "Model",
     *       "visible": true,
     *       "disabled": false,
     *     },
     *     ...
     * }
     *
     * @return array
     * @todo: add caching
     */
    public function get(): array
    {
        $connector = Connector::instance($this->serverId);
        $connector->connect();
        $query   = new DeviceListColumns();
        $columns = $connector->query($query);

        /** @var \idoit\Component\Settings\User $userSettings */
        $userSettings  = isys_application::instance()->container->get('settingsUser');
        $hiddenColumns = $userSettings->get('jdisc.device-list.hidden-columns', []);

        foreach ($columns as $fieldId => &$column) {
            $column['visible'] = !in_array($fieldId, $hiddenColumns);
            $column['disabled'] = in_array($fieldId, $this->alwaysVisibleColumns);
        }

        $columns['deviceId']['name'] = 'Id';

        return $columns;
    }

    /**
     * @param array $columns
     * @return int
     */
    public function hide(array $columns = []): int
    {
        $connector = Connector::instance($this->serverId);
        $connector->connect();

        $query            = new DeviceListColumns();
        $availableColumns = $connector->query($query);

        $columns = array_values(array_diff($columns, $this->alwaysVisibleColumns));
        $columns = array_intersect($columns, array_keys($availableColumns));

        isys_application::instance()->container->get('settingsUser')
            ->set('jdisc.device-list.hidden-columns', $columns);

        return count($columns);
    }
}
