
// JavaScript Document
// limited functionality
exports.onesignal_push_template = async function (options) {
    // get appid
    const appid = this.parseOptional(options.appid, '*', process.env.ONESIGNAL_APP_ID)
    console.log(options.appid + " => " + appid)


    const tname = this.parseRequired(options.tname, '*', 'Template name is mandatory')
    console.log(options.tname + " => " + tname)

    console.log('bindings: ' + JSON.stringify(options.bindings))

    const fetch = require('node-fetch');

    const url = 'https://api.onesignal.com/templates';
    const os_options = {
        method: 'POST',
        headers: {
            accept: 'application/json',
            Authorization: `Basic ${process.env.ONESIGNAL_REST_API_KEY}`,
            'Content-Type': 'application/json; charset=utf-8'
        },
        body: JSON.stringify({
            "name": tname,
            "app_id": appid,
            "contents": options.bindings,
            "target_channel": "push"
        })
    };


    return fetch(url, os_options)
        .then(res => {

            return res.json().then(json => {
                json.status = res.status; // Add status to json response
                return json;
            });
        })
        .catch(err => console.error('Error:', err));

}