/* Magic Mirror
 * Module: MMM-Fuel
 *
 * By fewieden https://github.com/fewieden/MMM-Fuel
 * MIT Licensed.
 */

const request = require("request");
const NodeHelper = require("node_helper");

module.exports = NodeHelper.create({

    baseUrl: "https://creativecommons.tankerkoenig.de/json/list.php?",

    start: function() {
        console.log("Starting module: " + this.name);
    },

    socketNotificationReceived: function(notification, payload) {
        if(notification === "CONFIG"){
            this.config = payload;
            this.getData();
            setInterval(() => {
                this.getData();
            }, this.config.updateInterval);
        }
    },

    getData: function() {
        var options = {
            url: this.baseUrl +
                "lat=" + this.config.lat +
                "&lng=" + this.config.lng +
                "&rad=" + this.config.radius +
                "&type=all" +
                "&apikey=" + this.config.api_key +
                "&sort=dist"
        };
        request(options, (error, response, body) => {
            if (response.statusCode === 200) {
                body = JSON.parse(body);
                if(body.ok) {
                    var price = body.stations.slice(0);
                    price.sort((a, b) => {
                        return a[this.config.sortBy] - b[this.config.sortBy];
                    });
                    this.sendSocketNotification("PRICELIST", {byPrice: price, byDistance: body.stations});
                } else {
                    console.log("Error no fuel data");
                }
            } else {
                console.log("Error getting fuel data " + response.statusCode);
            }
        });
    }
});
@@ -1209,87 +1209,918 @@
     
-var price = body.stations.slice(0);%0A                    price.sort((a, b) =%3E %7B%0A
+for(var i = body.stations.length - 1; i %3E= 0; i--)%7B%0A                        var zeroFlag = true;%0A                        for(var n = 0; n %3C this.config.types.length; n++)%7B%0A                            if(body.stations%5Bi%5D%5Bthis.config.types%5Bn%5D%5D %3E 0)%7B%0A                                zeroFlag = false;%0A                                break;%0A                            %7D%0A                        %7D%0A                        if(zeroFlag)%7B%0A                            body.stations.splice(i, 1);%0A                        %7D%0A                    %7D%0A                    var price = body.stations.slice(0);%0A                    price.sort((a, b) =%3E %7B%0A                        if(b%5Bthis.config.sortBy%5D == 0)%7B%0A                            return Number.MIN_SAFE_INTEGER;%0A                        %7D else if(a%5Bthis.config.sortBy%5D == 0)%7B%0A                            return Number.MAX_SAFE_INTEGER;%0A                        %7D else %7B%0A    
     
@@ -2193,16 +2193,42 @@
 ortBy%5D;%0A
+                        %7D%0A
         

handle 0€ prices from API