<?php

use idoit\Module\Check_mk\Model\StaticTag;

/**
 * i-doit
 *
 * API model for Check_MK static tags.
 *
 * @package    i-doit
 * @subpackage API
 * @author     Leonard Fischer <lfischer@i-doit.com>
 * @copyright  synetics GmbH
 * @since      1.10.2
 * @license    http://www.i-doit.com/license
 */
class isys_api_model_checkmk_statictag extends isys_api_model_checkmk implements isys_api_model_interface
{
    /**
     * @var isys_monitoring_dao_hosts
     */
    private $dao;

    /**
     * Validation.
     *
     * @var  array
     */
    protected $m_validation = [
        'read'   => [],
        'create' => [
            'data'
        ],
        'update' => [
            'id',
            'data'
        ],
        'delete' => []
    ];

    /**
     * Data formatting used in format methods.
     *
     * @var  array
     */
    protected $mapping = [
        'isys_check_mk_tags__id'                           => 'id',
        'isys_check_mk_tags__unique_name'                  => 'tag',
        'isys_check_mk_tags__display_name'                 => 'title',
        'isys_check_mk_tags__isys_check_mk_tag_groups__id' => 'group',
        'isys_check_mk_tags__exportable'                   => 'export',
        'isys_check_mk_tags__description'                  => 'description'
    ];

    /**
     * isys_api_model_checkmk_statictag constructor.
     *
     * @param isys_component_database $db
     */
    public function __construct(isys_component_database $db)
    {
        parent::__construct();

        $this->set_database($db);

        $this->dao = StaticTag::instance($this->m_db);
    }

    /**
     * Read static tags.
     *
     * @param  array $parameters
     *
     * @return array
     * @throws isys_exception_database
     */
    public function read($parameters)
    {
        $id = null;
        $tag = null;
        $return = [];

        if (isset($parameters['id'])) {
            $id = (int)$parameters['id'];
        } else if (isset($parameters['ids']) && is_array($parameters['ids'])) {
            $id = array_filter($parameters['ids'], function ($id) {
                return is_numeric($id) && $id > 0;
            });
        }

        if (isset($parameters['tag']) && !empty($parameters['tag'])) {
            $tag = $parameters['tag'];
        }

        $result = $this->dao->getTags($id, $tag);

        while ($row = $result->get_row()) {
            $row['isys_check_mk_tags__id'] = (int)$row['isys_check_mk_tags__id'];
            $row['isys_check_mk_tags__exportable'] = (bool)$row['isys_check_mk_tags__exportable'];
            $row['isys_check_mk_tags__isys_check_mk_tag_groups__id'] = (int)$row['isys_check_mk_tags__isys_check_mk_tag_groups__id'];

            $return[] = $this->formatByMapping($this->mapping, $row);
        }

        return $return;
    }

    /**
     * Create static tags.
     *
     * @param  array $parameters
     *
     * @return array
     * @throws isys_exception_api_validation
     * @throws isys_exception_dao
     * @throws isys_exception_database
     */
    public function create($parameters)
    {
        if (! isset($parameters['data']['tag']) || empty($parameters['data']['tag'])) {
            throw new isys_exception_api_validation('Mandatory parameter "tag" not found in your request.', isys_api_controller_jsonrpc::ERR_Parameters);
        }

        if (! isset($parameters['data']['title']) || empty($parameters['data']['title'])) {
            throw new isys_exception_api_validation('Mandatory parameter "title" not found in your request.', isys_api_controller_jsonrpc::ERR_Parameters);
        }

        $parameters['id'] = null;

        unset($parameters['data']['id']);

        if (!isset($parameters['data']['export'])) {
            $parameters['data']['export'] = true;
        }

        $return = $this->update($parameters);

        if ($return['id'] > 0) {
            $return['message'] = 'Static tag successfully created.';
        } else {
            $return['message'] = 'Static tag was not created.';
        }

        return $return;
    }

    /**
     * Update static tags.
     *
     * @param $parameters
     *
     * @return array
     * @throws isys_exception_api_validation
     * @throws isys_exception_dao
     * @throws isys_exception_database
     */
    public function update($parameters)
    {
        $data = [];

        unset($parameters['data']['id']);

        if (isset($parameters['id']) && is_numeric($parameters['id']) && $parameters['id'] > 0) {
            if ($this->dao->getTags($parameters['id'])->count() === 0) {
                throw new isys_exception_api_validation('The given ID does not exist.', isys_api_controller_jsonrpc::ERR_Parameters);
            }
        }

        if (isset($parameters['data']['tag'])) {
            $data['unique_name'] = isys_check_mk_helper_tag::prepare_valid_tag_name($parameters['data']['tag']);
        }

        if (isset($parameters['data']['title'])) {
            $data['display_name'] = trim($parameters['data']['title']);
        }

        if (isset($parameters['data']['group'])) {
            if (is_numeric($parameters['data']['group']) && $parameters['data']['group'] > 0) {
                $data['isys_check_mk_tag_groups__id'] = (int)$parameters['data']['group'];
            } else {
                $data['isys_check_mk_tag_groups__id'] = isys_cmdb_dao_dialog::instance($this->m_db)->check_dialog('isys_check_mk_tag_groups', $parameters['data']['group']);
            }
        }

        if (isset($parameters['data']['export'])) {
            // We cast to boolean and then to integer, becuase the DB field is a tinyint 1.
            $data['exportable'] = (int)(bool)$parameters['data']['export'];
        }

        if (isset($parameters['data']['description'])) {
            $data['description'] = $parameters['data']['description'];
        }

        $id = (int)$this->dao->saveTag($parameters['id'], $data);

        return [
            'id'      => $id,
            'message' => ($id > 0 ? 'Static tag successfully updated.' : 'Static tag was not updated'),
            'success' => ($id > 0)
        ];
    }

    /**
     * Delete one or multiple static tags.
     *
     * @param  array $parameters
     *
     * @return array
     * @throws isys_exception_dao
     */
    public function delete($parameters)
    {
        $id = null;

        if (isset($parameters['id'])) {
            $id = (int)$parameters['id'];
        } else if (isset($parameters['ids']) && is_array($parameters['ids'])) {
            $id = array_filter($parameters['ids'], function ($id) {
                return is_numeric($id) && $id > 0;
            });
        } else {
            return [
                'success' => true,
                'message' => 'Nothing happened, you need to provide "id" or "ids" parameter.'
            ];
        }

        if ($this->dao->deleteTags($id)) {
            return [
                'success' => true,
                'message' => 'Static tags have been deleted.'
            ];
        } else {
            return [
                'success' => false,
                'message' => 'Static tags have not been deleted.'
            ];
        }
    }
}
