<?php

// SPDX-FileCopyrightText: 2022 Icinga GmbH <https://icinga.com>
// SPDX-License-Identifier: GPL-3.0-or-later

namespace Icinga\Module\Cube\IcingaDb;

use Icinga\Module\Cube\CubeRenderer\HostStatusCubeRenderer;
use Icinga\Module\Icingadb\Model\Host;
use Icinga\Module\Icingadb\Model\HoststateSummary;
use ipl\Stdlib\Filter;

class IcingaDbHostStatusCube extends IcingaDbCube
{
    public function getRenderer()
    {
        return new HostStatusCubeRenderer($this);
    }

    public function getAvailableFactColumns()
    {
        return [
            'hosts_cnt' => 'hosts_total',
            'hosts_down' => 'hosts_down_handled + f.hosts_down_unhandled',
            'hosts_unhandled_down' => 'hosts_down_unhandled',
            'hosts_pending' => 'hosts_pending',
        ];
    }

    public function createDimension($name)
    {
        $this->registerAvailableDimensions();

        if (isset($this->availableDimensions[$name])) {
            return clone $this->availableDimensions[$name];
        }

        return new CustomVariableDimension($name);
    }

    public function listAvailableDimensions()
    {
        return $this->fetchHostVariableDimensions();
    }

    public function prepareInnerQuery()
    {
        $query = HoststateSummary::on($this->getDb());
        $query->columns(array_diff_key($query->getModel()->getColumns(), (new Host())->getColumns()));
        $query->disableDefaultSort();
        $this->applyRestrictions($query);

        $this->innerQuery = $query;
        return $this->innerQuery;
    }

    /**
     * Return Filter for Hosts cube.
     *
     * @return Filter\Any|Filter\Chain
     */
    public function getObjectsFilter()
    {
        if ($this->objectsFilter === null) {
            $this->finalizeInnerQuery();

            $hosts = $this->innerQuery()->columns(['host' => 'host.name']);
            $hosts->getSelectBase()->resetGroupBy();

            $filter = Filter::any();

            foreach ($hosts as $object) {
                $filter->add(Filter::equal('host.name', $object->host));
            }

            $this->objectsFilter = $filter;
        }

        return $this->objectsFilter;
    }
}
