<?php

use idoit\Console\Command\Import\Csv\ImportCsvCommand;
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      Selcuk Kekec <skekec@i-doit.com>
 * @copyright   synetics GmbH
 * @license     http://www.i-doit.com/license
 */
class isys_handler_csv_import extends isys_handler
{
    /**
     * Desctructs this object
     *
     * @author Selcuk Kekec <skekec@i-doit.com>
     */
    public function __destruct()
    {
        if (empty($_SERVER['HTTP_HOST'])) {
            $this->logout();
        }
    }

    /**
     * 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.
     *
     * @author  Leonard Fischer <lfischer@i-doit.com>
     * @return  boolean
     */
    public function init()
    {
        global $argv, $g_comp_session;

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

            $file = null;
            $profileId = null;
            $delimiter = ';';
            $multiValueMode = 'row';

            if (!empty($_SERVER['HTTP_HOST'])) {
                $output = new BufferedOutput();
                $file = $_GET['file'];
                $profileId = $_GET['profileID'];
            } else {
                $output = new ConsoleOutput();
                // Set configuration variables.
                if (is_array($argv)) {
                    $cmd = $argv;
                    $file = $cmd[0];
                    $profileId = $cmd[1];
                    $delimiter = $cmd[2];
                    $multiValueMode = $cmd[3];
                }
            }

            $output->writeln('<error>isys_handler_csv_import is deprecated, please use php console.php import-csv instead</error>');

            $commandParams = [
                'command'    => 'import-csv',
                '--user'     => 'loginBefore',
                '--password' => 'loginBefore',
                '--tenantId' => 'loginBefore'
            ];

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

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

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

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

            /**
             * @var $command \idoit\Console\Command\AbstractCommand
             */
            $command = new ImportCsvCommand();
            $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;

        if (!isset($_SERVER['HTTP_HOST']) && !$g_comp_session->is_logged_in()) {
            if (!defined("C__CSV_HANDLER__IMPORT")) {
                verbose('CSV-Import handler configuration not loaded. Check the example in "' . BASE_DIR .
                    'src/handler/config/examples/isys_handler_import.inc.php" and copy it to "' . BASE_DIR . 'src/handler/config".');
            } else {
                error('Please login.');
            }

            die;
        }
    }
}
