<?php
namespace App\Models;

use CodeIgniter\Model;
class BackendModel extends Model
{

    const DEBUG_API_CALLS = false;
    private $wrenchboard;  // internal use only - no overriding
    public $USER = 'root';
    public function __construct()
    {
        $USER = $_SERVER['SCRIPT_FILENAME'];
        $USER = str_replace('/home', '', $USER);
        $USER = strtok($USER, '/');
        if ($USER=='opt') $USER = 'root';
        // Load API class
        $USER = 'root';
        $this->USER = $USER;

    }


    public function wrenchboard_api($in, &$out = array()) {
        log_message('critical', "wrenchboard_api-STARTING" );
        $ret = -1;

        $this->wrenchboard_load();
        if (!is_array($in)) {
            $in = array();
        }

        if (!is_array($out)) {
            $out = array();
        }

        if (self::DEBUG_API_CALLS) {
            $stack = debug_backtrace();

            $log = json_encode($stack);
            log_message('critical', "wrenchboard_api-FAIL".$log );

            error_log(json_encode($in));
        }
        log_message('critical', "wrenchboard_api-CALLED*****" );
        $ret = $this->wrenchboard->wrenchboard_api($in, $out);
        log_message('critical', "wrenchboard_api-RETURN*****" );
        return $ret;
    }

    public function logMessage($str) {
        $this->wrenchboard_load();
        if ($str == NULL || trim($str) == '') {
            return NULL;
        }
        if (self::DEBUG_API_CALLS) {
            $stack = debug_backtrace();
            $log = json_encode($stack);
            error_log($log);
            error_log($str);
        }
        $ret = $this->wrenchboard->logMessage($str);
        return $ret;
    }

    public function cfgReadChar($str) {
        $this->wrenchboard_load();
        if ($str == NULL || trim($str) == '') {
            return NULL;
        }
        if (self::DEBUG_API_CALLS) {
            $stack = debug_backtrace();
            $log = json_encode($stack);
            error_log($log);
            error_log($str);
        }
        $ret = $this->wrenchboard->cfgReadChar($str);
        return $ret;
    }

    public function cfgReadLong($str) {
        $this->wrenchboard_load();
        if ($str == NULL || trim($str) == '') {
            return 0;
        }
        if (self::DEBUG_API_CALLS) {
            $stack = debug_backtrace();
            $log = json_encode($stack);
            error_log($log);
            error_log($str);
        }
        $ret = $this->wrenchboard->cfgReadLong($str);
        return $ret;
    }

    private function wrenchboard_load() {
        $wrenchboard_class = 'wrenchboard_api_' . $this->USER . '\\WrenchBoard';
        if (!is_object($this->wrenchboard)) {
            $this->wrenchboard = new $wrenchboard_class();
        }
    }
}
