<?php

namespace api\v2;
use api\v2\Base;
use Exception;

use function api\v2\import_common;
import_common();
require_once(dirname(__FILE__) . '/../../../../includes/utils-smart-dashboards.inc.php');

/**
 * Manages dashlets including retrieval, creation, deletion, and updates.
 */
class dashlets extends Base {

    /**
     * Auth function for post request method on api/v2/account/dashlets 
     * All necessary auth is done in check_authentication so this just returns true.
     */
    public function authorized_for_post() {
        return true;
    }

    /**
     * Adds a new dashlet with provided parameters.
     * @return array Confirmation message of dashlet creation.
     */
    public function post() {
        check_nagios_session_protector();

        $boardid = grab_request_var("boardid", 0);
        if (empty($boardid)) {
            throw new Exception(_("No board ID specified!"), 500);
        }

        $name = grab_request_var("name", "");
        if (empty($name)) {
            throw new Exception(_("No name specified!"), 500);
        }

        $title = grab_request_var("title", "");
        if (empty($title)) {
            throw new Exception(_("No title specified!"), 500);
        }

        $opts = grab_request_var("opts", array());
        $args = grab_request_var("args", array());

        if(strpos($boardid, 'smart_') === 0){
            $boardid = substr($boardid, 6);
            add_dashlet_to_smart_dashboard($boardid, $name, $title, $args);
        } 
        else {
            add_dashlet_to_dashboard(0, $boardid, $name, $title, $opts, $args);
        }

        return ["message" => _("Successfully added dashlet")];
    }

}