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

    let limit = this.parseOptional(options.limit, '*', '50')
    console.log(options.limit + " => " + limit)

    let offset = this.parseOptional(options.offset, '*', '0')
    console.log(options.offset + " => " + offset)

    let channel = this.parseOptional(options.channel, '*', null)
    console.log(options.channel + " => " + channel)


    const fetch = require('node-fetch');
    if (channel == 'all' || channel == null) {
        selected_channel = null
    }
    else {
        selected_channel = `&channel=${channel}`
    }
    let url = `https://api.onesignal.com/templates?app_id=${appid}&limit=${limit}${selected_channel}`;

    // &channel=${channel}
    console.log(url)
    const os_options = {
        method: 'GET',
        headers: {
            accept: 'application/json',
            Authorization: `Basic ${process.env.ONESIGNAL_REST_API_KEY}`,
            'Content-Type': 'application/json; charset=utf-8'
        }
    };

    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));

}