<?php

use idoit\Module\Cmdb\Component\CategoryChanges\Changes;

/**
 * i-doit
 *
 * CMDB Action Processor
 *
 * @package     i-doit
 * @subpackage  CMDB
 * @author      Dennis Stücken <dstuecken@i-doit.de>
 * @version     1.0
 * @copyright   synetics GmbH
 * @license     http://www.i-doit.com/license
 */
class isys_cmdb_action_category
{
    /**
     * Instance of isys_component_dao_lock.
     *
     * @var  isys_component_dao_lock
     */
    protected $m_dao_lock;

    /**
     * Constructor.
     */
    public function __construct()
    {
        global $g_comp_database;

        $this->m_dao_lock = new isys_component_dao_lock($g_comp_database);
    }

    /**
     * Callback function called by rank_records.
     *
     * @param   $p_object_id
     * @param   $p_category_const
     *
     * @return  boolean
     * @author  Selcuk Kekec <skekec@i-doit.com>
     */
    public function check_right($p_object_id, $p_category_const)
    {
        return isys_auth_cmdb::instance()
            ->has_rights_in_obj_and_category(isys_auth::EDIT, $p_object_id, $p_category_const);
    }

    /**
     * Checks if the object is locked. Returns true, if object is locked for the current user - false, if not.
     *
     * @return  boolean
     */
    protected function object_is_locked()
    {
        if ($this->m_dao_lock->check_lock($_GET[C__CMDB__GET__OBJECT])) {
            isys_component_template_infobox::instance()
                ->set_message("<b>ERROR! - " . isys_application::instance()->container->get('language')
                        ->get("LC__OBJECT_LOCKED") . " (Lock-Timeout: " . C__LOCK__TIMEOUT . "s)</b>", null, null, null, defined_or_default('C__LOGBOOK__ALERT_LEVEL__3', 3));

            return true;
        }

        return false;
    }


    /**
     * Format the users changes by processing the _SM2_FORM data and compare them with the post array.
     *
     * @param array         $p_posts
     * @param isys_cmdb_dao $p_dao
     *
     * @return Changes
     * @throws Exception
     */
    public function format_changes($p_posts, $p_dao)
    {
        global $g_SM2_FORM;

        if (is_array($g_SM2_FORM) && is_array($p_posts) && $p_dao instanceof \isys_cmdb_dao_category) {
            $l_sm2 = $g_SM2_FORM;
            $entryId = $_GET[C__CMDB__GET__CATLEVEL] ?: $p_posts[C__GET__ID];

            if (is_array($entryId)) {
                $entryId = current($entryId);
            }

            if (is_numeric($entryId)) {
                $entryId = (int)$entryId;
            } else {
                $entryId = null;
            }

            // Starting point to process the changes
            $changer = Changes::instance($p_dao, $_GET[C__CMDB__GET__OBJECT], $entryId, [], [], $l_sm2, $p_posts);
            $changer->processChanges();

            return $changer;
        }

        throw new Exception('Changes could not be calculated!');
    }
}
