const omnis_calls = require('omnis_calls');
http = require('http');
https = require('https');
const crypto = require('crypto')
const fs = require('fs');
const os = require('os');
const path = require('path');
var logoMessage = "";
var logos = [];

const methodMap = {

    processLogos: function(param, response) {

        function getLogoDiectory(){
                return param.C1;
        }

        function whatLogosExist(path) {
            var results = []
            var files = fs.readdirSync(path);
            for (var i = 0; i < files.length; i++) {
                if (files[i] != "catalog.json" && files[i] != ".DS_Store" && files[i] != "manifest.json") {
                    temp = files[i];
                    temp = temp.split("_");
                    results.push(temp[1]);
                }
            }
            return results;
        }

        async function downloadMissingLogos(logos,logoscat) {
            let promises = logos.map((logoID) => {
                return new Promise((resolve, reject) => {
                    let file = fs.createWriteStream(getLogoDiectory() + "LogoCDM_" + logoID + "_545x204.png");
                    https.get("https://logos.suran.com/cdm/LogoCDM_"+logoID+"_545x204.png", function (resp) {
                        resp.pipe(file);
                        file.on('finish', function () {
                            file.close();
                            if(logoscat[logoscat.map(function(e) { return e.ID; }).indexOf(parseInt(logoID))].checksum != generateChecksum(logoID)){
                                logoMessage=logoMessage+logoID+" "
                                deleteLogos(logoID);
                            }
                            resolve(logoID);
                        });
                    });
                });
            });

            Promise.all(promises).then((values) => {
                param.dataToReturn = (logoMessage.length > 0) ? "Failed to download "+logoMessage : "Empty logoArray.";
                return omnis_calls.sendResponse(param,response);
            });
        }

        function deleteLogos(logoID){
            var path = getLogoDiectory()+"LogoCDM_"+logoID+"_545x204.png";
            try {
                fs.unlinkSync(path);
              } catch(err) {
                console.error(err);
              }
        }

        function getLogos() {
            let file2 = fs.createWriteStream(param.C1+"catalog.json");
            https.get('https://logos.suran.com/cdm/catalog.json', (resp) => {
                resp.pipe(file2);
                let data = '';
                resp.on('data', (chunk) => {
                    data += chunk;
                });

                resp.on('end', () => {
                    logos = JSON.parse(data);
                    logosID = logos.map(val => val.ID + "");
                    var logosWeHave = whatLogosExist(getLogoDiectory());

                    var logosWeNeed = logosID.filter(val => {
                        return (!logosWeHave.includes(val));
                    });

                    var logosWeDontNeed = [];
                    var logosWeNeed2 = [];
                    for(var i = 0; i<logosWeHave.length; i++){
                        if(logos.filter(item => item.ID === parseInt(logosWeHave[i])).length == 0)
                            deleteLogos(logosWeHave[i]);
                        else if(logos[logos.map(function(e) { return e.ID; }).indexOf(parseInt(logosWeHave[i]))].checksum != generateChecksum(logosWeHave[i]))
                            logosWeNeed2.push(parseInt(logosWeHave[i]));
                    }
                    logosWeNeed = logosWeNeed.concat(logosWeNeed2);

                    if (logosWeNeed.length > 0) {
                        downloadMissingLogos(logosWeNeed,logos);
                    }
                    else {
                        omnis_calls.sendResponse(param, response);
                    }
                });
            });
        }
        function generateChecksum(logoID){
            files = fs.readFileSync(getLogoDiectory()+"LogoCDM_"+logoID+"_545x204.png");
            const sha1sum = crypto.createHash('sha256').update(files).digest("hex");
            return sha1sum;
        }
        getLogos();
    }
};

module.exports = {
    call: function (method, param, response) { // The only requirement of an Omnis module is that it implement this function.

        autoSendResponse = false; // caa - we gonna handle the response ourselves

        if (methodMap[method]) {
            const result = methodMap[method](param, response);
            if (autoSendResponse)
                omnis_calls.sendResponse(result, response);
            return true;
        }
        else {
            throw Error("Method '" + method + "' does not exist");
        }

    }
};