const https = require('follow-redirects').https;
const http = require('follow-redirects').http;
const async = require('async');
const axios = require('axios');

const args = process.argv.slice(2);
const saveEndpoint = args.shift();

const saveDetail = (postData) => {

    let config = {
        method: 'post',
        maxBodyLength: Infinity,
        url: saveEndpoint,
        headers: { 
            'Content-Type': 'application/json'
        },
        data: postData
      };

      return  axios.request(config);
}

const getDetail = (id) => {
    var options = {
        'method': 'GET',
        'hostname': 'api.printify.com',
        'path': '/v1/catalog/blueprints/' + id + '.json',
        'maxRedirects': 20,
        'headers': {
            'Authorization': 'Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiJ9.eyJhdWQiOiIzN2Q0YmQzMDM1ZmUxMWU5YTgwM2FiN2VlYjNjY2M5NyIsImp0aSI6ImY5MzI4NWZmYTVkNGY0OTNjODA4ZjA5ZjQzNDhmNjU5NzE4YzRlNjhmNjg5NGM5OWM4OWNmYjFiMjAwNmFiNDc4ZGE5NzYxNGQzYjY2MDI1IiwiaWF0IjoxNjk0MzM4Mzg3LjY0MzE3OSwibmJmIjoxNjk0MzM4Mzg3LjY0MzE4MywiZXhwIjoxNzI1OTYwNzg3LjYzNzk1Nywic3ViIjoiODc1MjIyNiIsInNjb3BlcyI6WyJzaG9wcy5tYW5hZ2UiLCJzaG9wcy5yZWFkIiwiY2F0YWxvZy5yZWFkIiwib3JkZXJzLnJlYWQiLCJvcmRlcnMud3JpdGUiLCJwcm9kdWN0cy5yZWFkIiwicHJvZHVjdHMud3JpdGUiLCJ3ZWJob29rcy5yZWFkIiwid2ViaG9va3Mud3JpdGUiLCJ1cGxvYWRzLnJlYWQiLCJ1cGxvYWRzLndyaXRlIiwicHJpbnRfcHJvdmlkZXJzLnJlYWQiXX0.AEdc7qUcMb-lLFNOg1Jj2Evpis3G6zLRxeVsDFkyPB_3b-PIfuv7aVeDzwN3qf1VvYONHNeuoyX9Dcd_wg0',
        },
    };

    return new Promise((resolve, reject) => {
        const req = http.request(options, function (res) {
            const chunks = [];

            res.on("data", function (chunk) {
                chunks.push(chunk);
            });

            res.on("end", function (chunk) {
                const body = Buffer.concat(chunks);
                resolve(body.toString());
            });

            res.on("error", function (error) {
                console.error(error);
                reject(error);
            });
        });

        req.end();
    })
}

const queue = async.queue((task, completed) => {
    console.log("Currently Busy Processing Task " + task);

    getDetail(task).then((result) => {

        saveDetail({
            blueprint: JSON.parse(result)
        }).then((data) => {
            const remaining = queue.length();
            completed(null, { task, remaining });
        }).catch((err) => {
            console.error("Error at", task, err);
        });

    }).catch((err) => {
        console.error("Error at", task, err);
    });

}, 5);

for (let i = 0; i < args.length; i++) {
    const blueprintId = args[i];
    queue.push(blueprintId, (error, { task, remaining }) => {
        if (error) {
            console.log(`An error occurred while processing task ${task}`);
        } else {
            console.log(`Finished processing task ${task}
                   . ${remaining} tasks remaining`);
        }
    });

}