/* global Bdf,$$ */
/**
 * Objet global définissant l'espace de nom PlantUml
 * 
 * @namespace Pioche
 */
var PlantUml = {};

PlantUml.WORKER_URL = "third-lib/jsdeflate/rawdeflate.js";
PlantUml.PLANTUML_URL = "http://www.plantuml.com/plantuml/img/";

PlantUml.init = function () {
    
    var $pumlList = $$({role: "puml"});
    var nextIndex = 0;
    var $currentPuml;
    var deflater =new Worker(PlantUml.WORKER_URL);
    deflater.onmessage = function (e) {
        $currentPuml.after($("<img>").attr("src", PlantUml.PLANTUML_URL +_encode64(e.data)));
        _runNext();
    };
    _runNext();


    function _runNext() {
        if ($pumlList.length <= nextIndex) {
            return;
        }
        $currentPuml = $($pumlList[nextIndex]);
        nextIndex++;
        var s = unescape(encodeURIComponent($currentPuml.val()));
        deflater.postMessage(s);
    }
    
    function _encode64(data) {
        let r = "";
        for (let i = 0; i < data.length; i += 3) {
            if (i+2 === data.length) {
                r += _append3bytes(data.charCodeAt(i), data.charCodeAt(i+1), 0);
            } else if (i+1 === data.length) {
                r += _append3bytes(data.charCodeAt(i), 0, 0);
            } else {
                r += _append3bytes(data.charCodeAt(i), data.charCodeAt(i+1), data.charCodeAt(i+2));
            }
       }
       return r;
    }
    
    function _append3bytes(b1, b2, b3) {
        let c1 = b1 >> 2;
        let c2 = ((b1 & 0x3) << 4) | (b2 >> 4);
        let c3 = ((b2 & 0xF) << 2) | (b3 >> 6);
        let c4 = b3 & 0x3F;
        let r = "";
        r += _encode6bit(c1 & 0x3F);
        r += _encode6bit(c2 & 0x3F);
        r += _encode6bit(c3 & 0x3F);
        r += _encode6bit(c4 & 0x3F);
        return r;
    }
    
    function _encode6bit(b) {
        if (b < 10) {
            return String.fromCharCode(48 + b);
        }
        b -= 10;
        if (b < 26) {
            return String.fromCharCode(65 + b);
        }
        b -= 26;
        if (b < 26) {
            return String.fromCharCode(97 + b);
        }
        b -= 26;
        if (b === 0) {
            return '-';
        }
        if (b === 1) {
            return '_';
        }
        return '?';
    }
    
};


$(function () {
    PlantUml.init();
});
