<?php
/**
 * i-doit - Documentation and CMDB solution for IT environments
 *
 * This file is part of the i-doit framework. Modify at your own risk.
 *
 * Please visit http://www.i-doit.com/license for a full copyright and license information.
 *
 * @version     1.10
 * @package     i-doit
 * @author      synetics GmbH
 * @copyright   synetics GmbH
 * @url         http://www.i-doit.com
 * @license     http://www.i-doit.com/license
 */
use idoit\Console\Command\Import\ImportCommand;
use idoit\Console\IdoitConsoleApplication;
use Symfony\Component\Console\Input\ArrayInput;
use Symfony\Component\Console\Output\BufferedOutput;
use Symfony\Component\Console\Output\ConsoleOutput;

/**
 * i-doit
 *
 * Import handler
 *
 * @package    i-doit
 * @subpackage Handler
 * @author     Dennis Stücken <dstuecken@i-doit.org>
 * @copyright  synetics GmbH
 * @license    http://www.i-doit.com/license
 *
 * @deprecated Use ImportCommand instead
 */
class isys_handler_import extends isys_handler
{
    /**
     * Log
     *
     * @var isys_import_log
     */
    protected $m_log;

    /**
     * Desctructs this object
     *
     */
    public function __destruct()
    {
        if (empty($_SERVER['HTTP_HOST']))
        {
            $this->logout();
        }
        $this->m_log->flush_verbosity(true, false);
    }

    /**
     * Initializes the handler.
     *
     *  A login is always needed here because controller.php?load=handler is
     *  also reachable from outside (webserver) without any permission checks.
     *  To prevent a flood attack or any other malicious attack, change the view
     *  permission of controller.php in .htaccess.
     *
     * @return bool Success?
     */
    public function init()
    {
        global $argv, $g_comp_session;

        if ($g_comp_session->is_logged_in())
        {
            $application = new IdoitConsoleApplication();
            $application->setAutoExit(false);

            $file        = null;
            $type        = null;
            $objectType = null;
            $cmd         = null;

            if (!empty($_SERVER['HTTP_HOST']))
            {
                $output = new BufferedOutput();
                $file        = $_GET['file'];
                $type        = $_GET['type'];
                $objectType = $_GET['obj_type'];
            } else {
                $output = new ConsoleOutput();
                if (is_array($argv))
                {
                    $cmd  = $argv;
                    $file = $cmd[0];
                    $type = $cmd[1];
                    $objectType = $cmd[2];
                }
                else
                {
                    return false;
                }
            }

            $typeMapping = [
                'cmdb' => 'import-xml',
                'hinventory' => 'import-hinventory'
            ];

            $output->writeln('<error>isys_handler_import is deprecated, please use php console.php ' . $typeMapping[$type] . ' instead</error>');

            $objectId = null;

            if (!is_numeric($objectType))
            {
                $objectType = C__OBJTYPE__CLIENT;
                (!empty($_GET['force'])) ? $force = true : $force = $cmd[2];

                (!empty($_GET['object_id__HIDDEN'])) ? $objectId = $_GET['object_id__HIDDEN'] : $objectId = $cmd[3];

            } else {
                (!empty($_GET['force'])) ? $force = true : $force = $cmd[3];
                if (is_numeric($force)) $force = false;

                (!empty($_GET['object_id__HIDDEN'])) ? $objectId = $_GET['object_id__HIDDEN'] : $objectId = (isset($cmd[4])) ? $cmd[4] : $cmd[3];
            }

            if ($force == '--force')
            {
                $force = true;
            }

            $commandParams = [
                'command' => $typeMapping[$type],
                '--importFile' => $file,
                '--user' => 'loginBefore',
                '--password' => 'loginBefore',
                '--tenantId' => 'loginBefore'
            ];

            if ($objectType) {
                $commandParams['--objectType'] = $objectType;
            }

            if ($objectId) {
                $commandParams['--objectId'] = $objectId;
            }

            if ($force) {
                $commandParams['--force'] = $force;
            }

            /**
             * @var $command \idoit\Console\Command\AbstractCommand
             */
            $command = $application->find($typeMapping[$type]);
            $command->setSession($g_comp_session);
            $command->setContainer(\isys_application::instance()->container);
            $command->setAuth(\isys_auth_system::instance());

            $application->add($command);

            $application->run(new ArrayInput($commandParams), $output);

            if (!empty($_SERVER['HTTP_HOST'])) {
                echo $output->fetch();
            }

            return true;
        }

        return false;
    }

    /**
     * Constructs this object
     *
     */
    public function __construct()
    {
        global $g_comp_session;
        global $g_absdir;

        // Start logging:
        $this->m_log = isys_factory_log::get_instance('import_cmdb');

        if (!isset($_SERVER['HTTP_HOST']) && !$g_comp_session->is_logged_in())
        {
            if (!defined("C__HANDLER__IMPORT"))
            {
                $this->m_log->error(
                    sprintf(
                        'Import handler configuration not loaded. ' . "\nCheck the example in %s and copy it to %s.",
                        $g_absdir . '/src/handler/config/examples/isys_handler_import.inc.php',
                        $g_absdir . '/src/handler/config'
                    )
                );
            }
            else
            {
                error('Please login.');
            }
            exit(1);
        }
    }

}
