<?php

/*
 * Copyright 2005 - 2025 Centreon (https://www.centreon.com/)
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 * For more information : contact@centreon.com
 *
 */

namespace CentreonClapi;

use Centreon_Object_Relation_Instance_Resource;
use Centreon_Object_Resource;
use Exception;
use LogicException;
use PDOException;
use Pimple\Container;

require_once 'centreonObject.class.php';
require_once 'centreonInstance.class.php';
require_once 'Centreon/Object/Resource/Resource.php';
require_once 'Centreon/Object/Relation/Instance/Resource.php';

/**
 * Class
 *
 * @class CentreonResourceCfg
 * @package CentreonClapi
 */
class CentreonResourceCfg extends CentreonObject
{
    public const ORDER_UNIQUENAME = 0;
    public const ORDER_VALUE = 1;
    public const ORDER_INSTANCE = 2;
    public const ORDER_COMMENT = 3;
    public const MACRO_ALREADY_IN_USE = 'Resource is already tied to instance';

    /** @var string[] */
    public static $aDepends = ['INSTANCE'];

    /** @var CentreonInstance */
    protected $instanceObj;

    /** @var Centreon_Object_Relation_Instance_Resource */
    protected $relObj;

    /** @var */
    protected $instanceIds;

    /**
     * CentreonResourceCfg constructor
     *
     * @param Container $dependencyInjector
     *
     * @throws PDOException
     * @throws LogicException
     */
    public function __construct(Container $dependencyInjector)
    {
        parent::__construct($dependencyInjector);
        $this->instanceObj = new CentreonInstance($dependencyInjector);
        $this->relObj = new Centreon_Object_Relation_Instance_Resource($dependencyInjector);
        $this->object = new Centreon_Object_Resource($dependencyInjector);
        $this->params = ['resource_line' => '', 'resource_comment' => '', 'resource_activate' => '1'];
        $this->insertParams = [$this->object->getUniqueLabelField(), 'resource_line', 'instance_id', 'resource_comment'];
        $this->exportExcludedParams = array_merge($this->insertParams, [$this->object->getPrimaryKey()]);
        $this->nbOfCompulsoryParams = 4;
        $this->activateField = 'resource_activate';
        $this->action = 'RESOURCECFG';
    }

    /**
     * Magic method
     *
     * @param string $name
     * @param array $arg
     * @throws CentreonClapiException
     * @return void
     */
    public function __call($name, $arg)
    {
        // Get the method name
        $name = strtolower($name);
        // Get the action and the object
        if (preg_match('/^(get|set|add|del)([a-zA-Z_]+)/', $name, $matches)) {
            switch ($matches[2]) {
                case 'instance':
                    $class = 'Centreon_Object_Instance';
                    $relclass = 'Centreon_Object_Relation_Instance_Resource';
                    break;
                default:
                    throw new CentreonClapiException(self::UNKNOWN_METHOD);
                    break;
            }

            if (class_exists($relclass) && class_exists($class)) {
                // Parse arguments
                if (! isset($arg[0])) {
                    throw new CentreonClapiException(self::MISSINGPARAMETER);
                }
                $args = explode($this->delim, $arg[0]);

                $object = $this->object->getIdByParameter($this->object->getUniqueLabelField(), [$args[0]]);
                if (isset($object[0][$this->object->getPrimaryKey()])) {
                    $objectId = $object[0][$this->object->getPrimaryKey()];
                } else {
                    throw new CentreonClapiException(self::OBJECT_NOT_FOUND . ':' . $args[0]);
                }

                $relobj = new $relclass($this->dependencyInjector);
                $obj = new $class($this->dependencyInjector);
                if ($matches[1] == 'get') {
                    $tab = $relobj->getTargetIdFromSourceId(
                        $relobj->getFirstKey(),
                        $relobj->getSecondKey(),
                        $objectId
                    );
                    echo 'id' . $this->delim . 'name' . "\n";
                    foreach ($tab as $value) {
                        $tmp = $obj->getParameters($value, [$obj->getUniqueLabelField()]);
                        echo $value . $this->delim . $tmp[$obj->getUniqueLabelField()] . "\n";
                    }
                } else {
                    if (! isset($args[1])) {
                        throw new CentreonClapiException(self::MISSINGPARAMETER);
                    }
                    $relations = explode('|', $args[1]);
                    $relationTable = [];
                    foreach ($relations as $rel) {
                        $sRel = $rel;
                        if (is_string($rel)) {
                            $rel = htmlentities($rel, ENT_QUOTES, 'UTF-8');
                        }
                        $tab = $obj->getIdByParameter($obj->getUniqueLabelField(), [$rel]);
                        if (! count($tab)) {
                            throw new CentreonClapiException(self::OBJECT_NOT_FOUND . ':' . $sRel);
                        }
                        $relationTable[] = $tab[0];
                    }
                    if ($matches[1] == 'set') {
                        $relobj->delete(null, $objectId);
                    }
                    $existingRelationIds = $relobj->getTargetIdFromSourceId(
                        $relobj->getFirstKey(),
                        $relobj->getSecondKey(),
                        $objectId
                    );
                    foreach ($relationTable as $relationId) {
                        if ($matches[1] == 'del') {
                            $relobj->delete($relationId, $objectId);
                        } elseif ($matches[1] == 'set' || $matches[1] == 'add') {
                            if (! in_array($relationId, $existingRelationIds)) {
                                $relobj->insert($relationId, $objectId);
                            }
                        }
                    }
                }
            } else {
                throw new CentreonClapiException(self::UNKNOWN_METHOD);
            }
        } else {
            throw new CentreonClapiException(self::UNKNOWN_METHOD);
        }
    }

    /**
     * @param $parameters
     *
     * @throws CentreonClapiException
     * @throws PDOException
     * @return void
     */
    public function initInsertParameters($parameters): void
    {
        $params = explode($this->delim, $parameters);
        if (count($params) < $this->nbOfCompulsoryParams) {
            throw new CentreonClapiException(self::MISSINGPARAMETER);
        }

        if (! preg_match('/^\$\S+\$$/', $params[self::ORDER_UNIQUENAME])) {
            $params[self::ORDER_UNIQUENAME] = '$' . $params[self::ORDER_UNIQUENAME] . '$';
        }

        $addParams = [];
        $instanceNames = explode('|', $params[self::ORDER_INSTANCE]);

        $this->instanceIds = [];
        foreach ($instanceNames as $instanceName) {
            $this->instanceIds[] = $this->instanceObj->getInstanceId($instanceName);
        }

        foreach ($this->instanceIds as $instanceId) {
            if ($this->isUnique($params[self::ORDER_UNIQUENAME], $instanceId) == false) {
                throw new CentreonClapiException(self::MACRO_ALREADY_IN_USE);
            }
        }

        $addParams[$this->object->getUniqueLabelField()] = $params[self::ORDER_UNIQUENAME];
        $addParams['resource_line'] = $params[self::ORDER_VALUE];
        $addParams['resource_comment'] = $params[self::ORDER_COMMENT];
        $this->params = array_merge($this->params, $addParams);
    }

    /**
     * @param $resourceId
     */
    public function insertRelations($resourceId): void
    {
        $this->setRelations($resourceId, $this->instanceIds);
    }

    /**
     * @param $parameters
     * @throws CentreonClapiException
     * @return array
     */
    public function initUpdateParameters($parameters)
    {
        $params = explode($this->delim, $parameters);
        if (count($params) < self::NB_UPDATE_PARAMS) {
            throw new CentreonClapiException(self::MISSINGPARAMETER);
        }
        if (is_numeric($params[0])) {
            $objectId = $params[0];
        } else {
            $object = $this->object->getIdByParameter($this->object->getUniqueLabelField(), [$params[0]]);
            if (isset($object[0][$this->object->getPrimaryKey()])) {
                $objectId = $object[0][$this->object->getPrimaryKey()];
            } else {
                throw new CentreonClapiException(self::OBJECT_NOT_FOUND . ':' . $params[0]);
            }
        }
        if ($params[1] == 'instance') {
            $instanceNames = explode('|', $params[2]);
            $instanceIds = [];
            foreach ($instanceNames as $instanceName) {
                $instanceIds[] = $this->instanceObj->getInstanceId($instanceName);
            }
            $this->setRelations($objectId, $instanceIds);
        } else {
            $params[1] = str_replace('value', 'line ', $params[1]);
            if ($params[1] == 'name') {
                if (! preg_match('/^\$\S+\$$/', $params[2])) {
                    $params[2] = '$' . $params[2] . '$';
                }
            }
            $params[1] = 'resource_' . $params[1];
            $updateParams = [$params[1] => $params[2]];
            $updateParams['objectId'] = $objectId;

            return $updateParams;
        }

        return [];
    }

    /**
     * @param $parameters
     *
     * @throws CentreonClapiException
     * @throws PDOException
     */
    public function addPoller($parameters): void
    {
        $params = explode($this->delim, $parameters);
        if (count($params) < self::NB_UPDATE_PARAMS) {
            throw new CentreonClapiException(self::MISSINGPARAMETER);
        }

        if (is_numeric($params[0])) {
            $objectId = $params[0];
        } else {
            $object = $this->object->getIdByParameter($this->object->getUniqueLabelField(), [$params[0]]);
            if (isset($object[0][$this->object->getPrimaryKey()])) {
                $objectId = $object[0][$this->object->getPrimaryKey()];
            } else {
                throw new CentreonClapiException(self::OBJECT_NOT_FOUND . ':' . $params[0]);
            }
        }
        if ($params[1] == 'instance') {
            $instanceNames = explode('|', $params[2]);
            $instanceIds = [];
            foreach ($instanceNames as $instanceName) {
                $instanceId = $this->instanceObj->getInstanceId($instanceName);
                $stmt = $this->db->query('SELECT instance_id
                      FROM cfg_resource_instance_relations
                      WHERE instance_id = ?
                      AND resource_id = ?', [$instanceId, $objectId]);
                $results = $stmt->fetchAll();
                $oldInstanceIds = [];
                foreach ($results as $result) {
                    $oldInstanceIds[] = $result['instance_id'];
                }
                if (! in_array($instanceId, $oldInstanceIds)) {
                    $instanceIds[] = $instanceId;
                }
            }
            $this->addRelations($objectId, $instanceIds);
        }
    }

    /**
     * @param string $objectName
     * @throws CentreonClapiException
     */
    public function del($objectName): void
    {
        if (is_numeric($objectName)) {
            $objectId = $objectName;
        } else {
            if (! preg_match('/^\$\S+\$$/', $objectName)) {
                $objectName = '$' . $objectName . '$';
            }
            $object = $this->object->getIdByParameter($this->object->getUniqueLabelField(), [$objectName]);
            if (isset($object[0][$this->object->getPrimaryKey()])) {
                $objectId = $object[0][$this->object->getPrimaryKey()];
            } else {
                throw new CentreonClapiException(self::OBJECT_NOT_FOUND . ':' . $objectName);
            }
        }
        $this->object->delete($objectId);
    }

    /**
     * @param null $parameters
     * @param array $filters
     *
     * @throws Exception
     */
    public function show($parameters = null, $filters = []): void
    {
        $filters = [];
        if (isset($parameters)) {
            $filters = [$this->object->getUniqueLabelField() => '%' . $parameters . '%'];
        }
        $params = ['resource_id', 'resource_name', 'resource_line', 'resource_comment', 'resource_activate'];
        $paramString = str_replace('_', ' ', implode($this->delim, $params));
        $paramString = str_replace('resource ', '', $paramString);
        $paramString = str_replace('line', 'value', $paramString);
        echo $paramString . $this->delim . 'instance' . "\n";
        $elements = $this->object->getList($params, -1, 0, null, null, $filters);
        foreach ($elements as $tab) {
            $str = '';
            foreach ($tab as $key => $value) {
                $str .= $value . $this->delim;
            }
            $instanceIds = $this->relObj->getinstance_idFromresource_id(trim($tab['resource_id']));
            $strInstance = '';
            foreach ($instanceIds as $instanceId) {
                if ($strInstance != '') {
                    $strInstance .= '|';
                }
                $strInstance .= $this->instanceObj->getInstanceName($instanceId);
            }
            $str .= $strInstance;
            $str = trim($str, $this->delim) . "\n";
            echo $str;
        }
    }

    /**
     * @param null $filterName
     *
     * @throws Exception
     * @return int|void
     */
    public function export($filterName = null)
    {
        if (! $this->canBeExported($filterName)) {
            return 0;
        }

        $labelField = $this->object->getUniqueLabelField();
        $elements = $this->object->getList(
            '*',
            -1,
            0,
            $labelField,
            'ASC'
        );

        if (! is_null($filterName) && ! empty($filterName)) {
            $nbElements = count($elements);
            for ($i = 0; $i < $nbElements; $i++) {
                if ($elements[$i][$labelField] != $filterName) {
                    unset($elements[$i]);
                }
            }
        }

        foreach ($elements as $element) {
            $instanceIds = $this->relObj->getinstance_idFromresource_id(
                trim($element[$this->object->getPrimaryKey()])
            );

            // ADD action
            $addStr = $this->action . $this->delim . 'ADD';
            foreach ($this->insertParams as $param) {
                if ($param == 'instance_id') {
                    $instances = [];
                    foreach ($instanceIds as $instanceId) {
                        $instances[] = $this->instanceObj->getInstanceName($instanceId);
                    }
                    $element[$param] = implode('|', $instances);
                }
                $addStr .= $this->delim . $element[$param];
            }
            $addStr .= "\n";
            echo $addStr;

            // SETPARAM action
            foreach ($element as $parameter => $value) {
                if (! in_array($parameter, $this->exportExcludedParams) && ! is_null($value) && $value != '') {
                    $parameter = str_replace('resource_', '', $parameter);
                    $value = str_replace("\n", '<br/>', $value);
                    $value = CentreonUtils::convertLineBreak($value);
                    echo $this->action . $this->delim
                        . 'setparam' . $this->delim
                        . $element[$this->object->getPrimaryKey()] . $this->delim
                        . $parameter . $this->delim
                        . $value . "\n";
                }
            }
        }
    }

    /**
     * Checks if macro is unique on a given poller
     *
     * @param $macro
     * @param int $pollerId
     *
     * @throws CentreonClapiException
     * @throws PDOException
     * @return bool
     */
    protected function isUnique($macro, $pollerId)
    {
        if (is_numeric($macro)) {
            $stmt = $this->db->query('SELECT resource_name FROM cfg_resource WHERE resource_id = ?', [$macro]);
            $res = $stmt->fetchAll();
            if (count($res)) {
                $macroName = $res[0]['resource_name'];
            } else {
                throw new CentreonClapiException(self::OBJECT_NOT_FOUND);
            }
            unset($res, $stmt);

        } else {
            $macroName = $macro;
        }
        $stmt = $this->db->query('SELECT r.resource_id
                                  FROM cfg_resource r, cfg_resource_instance_relations rir
                                  WHERE r.resource_id = rir.resource_id
                                  AND rir.instance_id = ?
                                  AND r.resource_name = ?', [$pollerId, $macroName]);
        $res = $stmt->fetchAll();

        return ! (count($res));
    }

    /**
     * Set Instance relations
     *
     * @param int $resourceId
     * @param array $instances
     * @return void
     */
    protected function setRelations($resourceId, $instances)
    {
        $this->relObj->delete_resource_id($resourceId);
        foreach ($instances as $instanceId) {
            $this->relObj->insert($instanceId, $resourceId);
        }
    }
}
