const flowUtil = require("./util");
const credentials = require("../nodes/credentials");
const clone = require("clone");

/**
 * This class represents a group within the runtime.
 */
class Group {

    /**
     * Create a Group object.
     * @param {[type]} parent     The parent flow/group
     * @param {[type]} groupDef   This group's definition
     */
    constructor(parent, groupDef) {
        this.TYPE = 'group'
        this.name = groupDef.name
        this.parent = parent
        this.group = groupDef
        this.id = this.group.id
        this.g = this.group.g
        this.env = this.group.env
        this._env = {}
    }

    async start() {
        if (this.env) {
            this._env = await flowUtil.evaluateEnvProperties(this, this.env, credentials.get(this.id))
        }
    }
    /**
     * Get a group setting value.
     * @param  {[type]} key [description]
     * @return {[type]}     [description]
     */
    getSetting(key) {
        if (key === "NR_GROUP_NAME") {
            return this.name;
        }
        if (key === "NR_GROUP_ID") {
            return this.id;
        }
        if (!key.startsWith("$parent.")) {
            if (this._env.hasOwnProperty(key)) {
                return (this._env[key] && Object.hasOwn(this._env[key], 'value') && this._env[key].__clone__) ? clone(this._env[key].value) : this._env[key]
            }
        } else {
            key = key.substring(8);
        }
        return this.parent.getSetting(key);
    }

    error(msg) {
        this.parent.error(msg);
    }

    getContext(scope) {
        return this.parent.getContext(scope);
    }
}

module.exports = {
    Group
}
