
'use strict';
require('dotenv').config();
var request = require('request');

function getCatalog(list, iterator, callback){
        var doneCount = 0;
        var products = [];

        function report(data){
                products = products.concat(data);
                doneCount++;

                if(doneCount == list.length){
                        callback(products);
                }
        }

        for(var i=0; i < list.length; i++){
                iterator(list[i], report);
        }
}


function catalogRequest(url, report){
        // Make API request, and when done append results to products and call report()
        var options = {
                url: url
        };
        request.get(options, function(err, r, body){
                if(err){
                        console.log(err);
                } else {
                        // DO STUFF WITH REPLY HERE
                        var data = JSON.parse(body).products;
                        console.log(data.length);
                        console.log("Request: " + data[0].title);
                        report(data);
                }
        });
}

function sendCatalog(products){
        // Refactor variants & categories to array
        
        function refactorProduct(p){
                var cats = [];
                var variants = [];
                for(var c in p.categories){
                        if(p.categories.hasOwnProperty(c)){
                                cats.push(p.categories[c]);
                        }
                }
                for (var v in p.variants){
                        if(p.variants.hasOwnProperty(v)){
                                variants.push(p.variants[v]);
                        }
                }
                
                p.variants = variants;
                p.categories = cats;
                return p;
        }
        var refactored = products.map(refactorProduct);
        console.log(refactored[0]);
}

var apiUrl = process.env.URL;

var countOptions = {
        url: apiUrl + "catalog/count.json"
};


request.get(countOptions, function(err, r, body){
        if (err){
                console.log(err);
        } else {
                var countBody = JSON.parse(body);
                console.log(countBody);
                
                var n = Math.ceil(countBody.count/250);
                var pages = [];
                for (var i=1; i<=n; i++){
                   pages.push(apiUrl + "catalog.json?limit=250&page=" + i.toString());     
                }
                getCatalog(pages, catalogRequest, sendCatalog);
        }
});