<?php

namespace idoit\Module\Nagios\Console\Command;

use idoit\Console\Command\AbstractCommand;
use InvalidArgumentException;
use isys_component_dao_nagios;
use isys_exception_filesystem;
use isys_module_nagios;
use isys_monitoring_dao_hosts;
use Symfony\Component\Console\Input\InputDefinition;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;

class NagiosExportCommand extends AbstractCommand
{
    const NAME = 'nagios-export';

    /**
     * @var OutputInterface
     */
    private $output;

    /**
     * Nagios DAO
     *
     * @var  isys_component_dao_nagios
     */
    private $m_daoNagios;

    /**
     * Nagios Module
     *
     * @var  isys_module_nagios
     */
    private $m_moduleNagios;

    /**
     * Get name for command
     *
     * @return string
     */
    public function getCommandName()
    {
        return self::NAME;
    }

    /**
     * Get description for command
     *
     * @return string
     */
    public function getCommandDescription()
    {
        return 'Exports i-doit objects and monitoring settings to Nagios configuration files';
    }

    /**
     * Retrieve Command InputDefinition
     *
     * @return InputDefinition
     */
    public function getCommandDefinition()
    {
        $definition = new InputDefinition();

        $definition->addOption(new InputOption('nagiosHostId', null, InputOption::VALUE_REQUIRED, 'This will define, which nagios host will be used for the export.'));

        $definition->addOption(new InputOption('validate', null, InputOption::VALUE_NONE, 'Validate exported files'));

        return $definition;
    }

    /**
     * Checks if a command can have a config file via --config
     *
     * @return bool
     */
    public function isConfigurable()
    {
        return true;
    }

    /**
     * Returns an array of command usages
     *
     * @return string[]
     */
    public function getCommandUsages()
    {
        return [];
    }

    protected function execute(InputInterface $input, OutputInterface $output)
    {
        $this->output = $output;

        $this->output->writeln("Setting up system environment");

        // Get daos, because now we are logged in.
        $this->m_moduleNagios = new isys_module_nagios();
        $this->m_daoNagios = new isys_component_dao_nagios($this->container->database);

        $this->output->writeln("Nagios-Handler initialized (" . date("Y-m-d H:i:s") . ")");

        if (!$input->getOption('nagiosHostId')) {
            $output->writeln("Please specify a Nagios Host using the --nagiosHostId option! Try -n <nagios host id>");

            $l_res = isys_monitoring_dao_hosts::instance($this->container->database)
                ->get_export_data();

            if ($l_res->num_rows() > 0) {
                $l_host = [];

                while ($l_row = $l_res->get_row()) {
                    $l_host[] = ' - ' . $l_row['isys_monitoring_export_config__id'] . ': ' . $l_row['isys_monitoring_export_config__title'];
                }

                $output->writeln("Possible ID's are:");
                $output->writeln(implode("\n", $l_host));
            }

            return;
        }

        // Check status and add to logbook.
        try {
            $this->export($input->getOption('nagiosHostId'), $input->getOption('validate') ?: false);
        } catch (InvalidArgumentException $e) {
            $this->output->writeln('Invalid argument: ' . $e->getMessage());
        }
    }

    /**
     * Export method.
     *
     * @param   integer $p_host_id
     * @param   bool    $validate
     *
     * @throws  InvalidArgumentException
     */
    private function export($p_host_id, $validate)
    {
        $l_host = isys_monitoring_dao_hosts::instance($this->container->database)
            ->get_export_data($p_host_id);
        $l_hosts_number = $l_host->num_rows();

        if ($l_hosts_number != 1) {
            throw new InvalidArgumentException("Host #" . $p_host_id . " does not exist");
        }

        $l_row = $l_host->get_row();

        $this->output->writeln('Starting export for "' . $l_row['isys_monitoring_export_config__title'] . '"');

        if (empty($l_row["isys_monitoring_export_config__path"])) {
            $l_row["isys_monitoring_export_config__path"] = "nagiosexport";
        }

        $this->output->writeln('Exporting to directory "' . $l_row["isys_monitoring_export_config__path"] . '"');

        try {
            $this->m_moduleNagios->exportNagiosConfig($l_row, $validate);
        } catch (isys_exception_filesystem $e) {
            $this->output->writeln($e->getMessage());
        }

        $this->output->writeln("Done");
    }
}
