<?php
use Icinga\Module\Monitoring\Object\Host;
use Icinga\Module\Monitoring\Object\Service;
use Icinga\Web\Url;
use Icinga\Web\UrlParams;

function contactsLink($match, $view) {
    $links = array();
    foreach (preg_split('/,\s/', $match[1]) as $contact) {
        $links[] = $view->qlink(
            $contact,
            'monitoring/show/contact',
            array('contact_name' => $contact),
            array('title' => sprintf($view->translate('Show detailed information about %s'), $contact))
        );
    }
    return '[' . implode(', ', $links) . ']';
}

$self = $this;

$url = $this->url();
$limit = (int) $url->getParam('limit', 25);
if (! $url->hasParam('page') || ($page = (int) $url->getParam('page')) < 1) {
    $page = 1;
}

/** @var \Icinga\Module\Monitoring\DataView\EventHistory $history */
$history->limit($limit * $page);
?>
<div class="content">
<?php
$dateFormat = $this->translate('%A, %B %e, %Y', 'date.verbose');
$lastDate = null;
$flappingMsg = $this->translate('Flapping with a %.2f%% state change rate');
$rowAction = Url::fromPath('monitoring/event/show');
?>
    <?php foreach ($history->peekAhead() as $event): ?>
<?php if ($lastDate === null): ?>
    <table class="table-row-selectable state-table" data-base-target="_next">
        <tbody>
<?php endif;
        $icon = '';
        $iconTitle = null;
        $isService = isset($event->service_description);
        $msg = $event->output;
        $stateName = 'no-state';

        $rowAction->setParams(new UrlParams())->addParams(array(
            'type' => $event->type,
            'id' => $event->id
        ));
        switch ($event->type) {
            case substr($event->type, 0, 13) === 'notification_':
                $rowAction->setParam('type', 'notify');
                $icon = 'bell';
                switch (substr($event->type, 13)) {
                    case 'state':
                        $iconTitle = $this->translate('State notification', 'tooltip');
                        $label = $this->translate('NOTIFICATION');
                        $stateName = $isService ? Service::getStateText($event->state) : Host::getStateText($event->state);
                        break;
                    case 'ack':
                        $iconTitle = $this->translate('Ack Notification', 'tooltip');
                        $label = $this->translate('ACK NOTIFICATION');
                        break;
                    case 'dt_start':
                        $iconTitle = $this->translate('Downtime start notification', 'tooltip');
                        $label = $this->translate('DOWNTIME START NOTIFICATION');
                        break;
                    case 'dt_end':
                        $iconTitle = $this->translate('Downtime end notification', 'tooltip');
                        $label = $this->translate('DOWNTIME END NOTIFICATION');
                        break;
                    case 'flapping':
                        $iconTitle = $this->translate('Flapping notification', 'tooltip');
                        $label = $this->translate('FLAPPING NOTIFICATION');
                        break;
                    case 'flapping_end':
                        $iconTitle = $this->translate('Flapping end notification', 'tooltip');
                        $label = $this->translate('FLAPPING END NOTIFICATION');
                        break;
                    case 'custom':
                        $iconTitle = $this->translate('Custom notification', 'tooltip');
                        $label = $this->translate('CUSTOM NOTIFICATION');
                        break;
                }
                $msg = $msg ? preg_replace_callback(
                    '/^\[([^\]]+)\]/',
                    function($match) use ($self) { return contactsLink($match, $self); },
                    $msg
                ) : $this->translate('This notification was not sent out to any contact.');
                break;
            case 'comment':
                $icon = 'comment-empty';
                $iconTitle = $this->translate('Comment', 'tooltip');
                $label = $this->translate('COMMENT');
                break;
            case 'comment_deleted':
                $icon = 'cancel';
                $iconTitle = $this->translate('Comment removed', 'tooltip');
                $label = $this->translate('COMMENT DELETED');
                break;
            case 'ack':
                $icon = 'ok';
                $iconTitle = $this->translate('Acknowledged', 'tooltip');
                $label = $this->translate('ACKNOWLEDGED');
                break;
            case 'ack_deleted':
                $icon = 'ok';
                $iconTitle = $this->translate('Acknowledgement removed', 'tooltip');
                $label = $this->translate('ACKNOWLEDGEMENT REMOVED');
                break;
            case 'dt_comment':
                $icon = 'plug';
                $iconTitle = $this->translate('Downtime scheduled', 'tooltip');
                $label = $this->translate('SCHEDULED DOWNTIME');
                break;
            case 'dt_comment_deleted':
                $icon = 'plug';
                $iconTitle = $this->translate('Downtime removed', 'tooltip');
                $label = $this->translate('DOWNTIME DELETED');
                break;
            case 'flapping':
                $icon = 'flapping';
                $iconTitle = $this->translate('Flapping started', 'tooltip');
                $label = $this->translate('FLAPPING');
                $msg = sprintf($flappingMsg, $msg);
                break;
            case 'flapping_deleted':
                $icon = 'flapping';
                $iconTitle = $this->translate('Flapping stopped', 'tooltip');
                $label = $this->translate('FLAPPING STOPPED');
                $msg = sprintf($flappingMsg, $msg);
                break;
            case 'hard_state':
                if ((int) $event->state === 0) {
                    $icon = 'thumbs-up';
                } else {
                    $icon = 'warning-empty';
                }
                $iconTitle = $this->translate('Hard state', 'tooltip');
                $label = $isService ? Service::getStateText($event->state, true) : Host::getStateText($event->state, true);
                $stateName = $isService ? Service::getStateText($event->state) : Host::getStateText($event->state);
                break;
            case 'soft_state':
                $icon = 'spinner';
                $iconTitle = $this->translate('Soft state', 'tooltip');
                $label = $isService ? Service::getStateText($event->state, true) : Host::getStateText($event->state, true);
                $stateName = $isService ? Service::getStateText($event->state) : Host::getStateText($event->state);
                break;
            case 'dt_start':
                $icon = 'plug';
                $iconTitle = $this->translate('Downtime started', 'tooltip');
                $label = $this->translate('DOWNTIME START');
                break;
            case 'dt_end':
                $icon = 'plug';
                $iconTitle = $this->translate('Downtime ended', 'tooltip');
                $label = $this->translate('DOWNTIME END');
                break;
        } ?>
        <?php
        $currentDate = strftime($dateFormat, (int) $event->timestamp);
        if ($currentDate !== $lastDate):
            $lastDate = $currentDate;
        ?>
            <tr>
                <th colspan="2"><?= $currentDate ?></th>
            </tr>
        <?php endif ?>
        <tr href="<?= $rowAction ?>">
            <td class="state-col state-<?= $stateName ?>">
            <?php if ($history->getIteratorPosition() % $limit === 0): ?>
                <a id="page-<?= $history->getIteratorPosition() / $limit + 1 ?>"></a>
            <?php endif ?>
                <div class="state-label"><?= $this->escape($label) ?></div>
                <div class="state-meta"><?= $this->formatTime($event->timestamp) ?></div>
            </td>
            <td>
                <div class="history-message-container">
                <?php if ($icon): ?>
                    <div class="history-message-icon">
                        <?= $this->icon($icon, $iconTitle) ?>
                    </div>
                <?php endif ?>
                    <div class="history-message-output">
                    <?php if ($this->isOverview): ?>
                        <?php if ($isService) {
                            echo '<span class="service-on">';
                            echo sprintf(
                                $this->translate('%s on %s', 'service on host'),
                                $this->qlink(
                                    $event->service_display_name,
                                    'monitoring/service/show',
                                    [
                                        'host' => $event->host_name,
                                        'service' => $event->service_description
                                    ],
                                    [
                                        'title' => sprintf(
                                            $this->translate('Show detailed information for service %s on host %s'),
                                            $event->service_display_name,
                                            $event->host_display_name
                                        )
                                    ]
                                ),
                                $this->qlink(
                                    $event->host_display_name,
                                    'monitoring/host/show',
                                    ['host' => $event->host_name],
                                    [
                                        'title' => sprintf(
                                            $this->translate('Show detailed information for host %s'),
                                            $event->host_display_name
                                        )
                                    ]
                                )
                            );
                            echo '</span>';
                        } else {
                            echo $this->qlink(
                                $event->host_display_name,
                                'monitoring/host/show',
                                ['host' => $event->host_name],
                                [
                                    'title' => sprintf(
                                        $this->translate('Show detailed information for host %s'),
                                        $event->host_display_name
                                    )
                                ]
                            );
                        } ?>
                    <?php endif ?>
                        <?= $this->nl2br($this->createTicketLinks($this->markdown($msg, ['class' => 'overview-plugin-output']))) ?>
                    </div>
                </div>
            </td>
        </tr>
        <?php endforeach ?>
<?php if ($lastDate !== null): ?>
        </tbody>
    </table>
<?php endif ?>
<?php if ($history->hasMore()): ?>
    <div class="action-links">
    <?php if ($this->compact) {
        echo $this->qlink(
            $this->translate('Show More'),
            $url->without(array('showCompact', 'limit')),
            null,
            array(
                'class'             => 'action-link',
                'data-base-target'  => '_next'
            )
        );
    } else {
        echo $this->qlink(
            $this->translate('Load More'),
            $url->setAnchor('page-' . ($page + 1)),
            array('page' => $page + 1,),
            array('class' => 'action-link')
        );
    } ?>
    </div>
<?php endif ?>
</div>
