<?php
/**
 *
 *
 * @package     i-doit
 * @subpackage
 * @author      Denis Koroliov <dkorolov@i-doit.com>
 * @copyright   synetics GmbH
 * @license     http://www.i-doit.com/license
 */

namespace idoit\Module\Console\Steps\Sql;

use idoit\Module\Console\Steps\Message\ErrorLevel;
use idoit\Module\Console\Steps\Message\Messages;
use idoit\Module\Console\Steps\Message\StepMessage;
use isys_helper_install;

class InsertPersons extends SqlStep
{
    private $created = false;

    public function __construct($host, $rootName, $rootPassword, $db, $port)
    {
        parent::__construct($host, $rootName, $rootPassword, $db, $port);

        // Seems like the autoloader did not find the class.
        if (!class_exists(isys_helper_install::class)) {
            global $g_absdir;
            
            require_once $g_absdir . '/src/classes/helper/isys_helper_install.php';
        }
    }

    /**
     * Process the work
     *
     * @param Messages $messages
     *
     * @return mixed
     */
    public function process(Messages $messages)
    {
        $connection = $this->createConnection();
        if ($connection->connect_error || $connection->error) {
            $messages->addMessage(new StepMessage($this, 'Cannot connect to DB', ErrorLevel::FATAL));

            return false;
        }
        if ($connection->query(isys_helper_install::generatePersonsListDataQuery())) {
            $messages->addMessage(new StepMessage($this, 'Users was successfully added: ', ErrorLevel::INFO));

            $this->created = true;
        } else {
            $messages->addMessage(new StepMessage($this, "Can't add users to database. ", ErrorLevel::FATAL));
            return false;
        }

        return true;
    }

    /**
     * Undo the work
     *
     * @param Messages $messages
     *
     * @return mixed
     */
    public function undo(Messages $messages)
    {
        if (!$this->created) {
            return true;
        }
        $messages->addMessage(new StepMessage($this, 'Removing persons from database. ', ErrorLevel::INFO));
        $connection = $this->createConnection();
        if ($connection->error) {
            $messages->addMessage(new StepMessage($this, 'Cannot connect to DB', ErrorLevel::FATAL));

            return false;
        }

        if ($connection->query("DELETE FROM isys_cats_person_list") === false) {
            $messages->addMessage("Cannot delete users");

            return false;
        }

        return true;
    }

    /**
     * Get name of the step
     *
     * @return string
     */
    public function getName()
    {
        return 'Inserting persons to database: ';
    }
}
