window.bootstrap_offcanvas_timers = window.bootstrap_offcanvas_timers || {};
window.bootstrap_offcanvas_refs = window.bootstrap_offcanvas_refs || {};

function getIdentifier(id) {
    return "bootstrap-offcanvas-" + id;
}

function getElement(id) {
    return document.getElementById(getIdentifier(id));
}

export function setup(id, options, ref) {
    destroy(id);    
    var element = getElement(id);

    var oOptions = JSON.parse(options);
    var offcanvas = bootstrap.Offcanvas.getOrCreateInstance(element, oOptions);
    //setupTimer(id);
    window.bootstrap_offcanvas_refs[id] = ref;

    element.addEventListener("hidden.bs.offcanvas", function () {
        console.log("hidden " + id);
        if (window.bootstrap_offcanvas_refs) {
            if (window.bootstrap_offcanvas_refs[id]) {
                var dotNetRef = window.bootstrap_offcanvas_refs[id];
                dotNetRef.invokeMethodAsync("OnHidden");
            }
        }        
    });

    element.addEventListener("shown.bs.offcanvas", function () {
        console.log("shown " + id);
        if (window.bootstrap_offcanvas_refs) {
            if (window.bootstrap_offcanvas_refs[id]) {
                var dotNetRef = window.bootstrap_offcanvas_refs[id];
                dotNetRef.invokeMethodAsync("OnShown");
            }
        }
    });

}

export function destroy(id) {
    //clearTimer(id);    
    var element = getElement(id);
    var offcanvas = bootstrap.Offcanvas.getInstance(element);

    if (offcanvas != null && typeof offcanvas !== 'undefined') {
        if (window.bootstrap_offcanvas_refs) {
            if (window.bootstrap_offcanvas_refs[id]) {
                //delete window.bootstrap_offcanvas_refs[id];                
            }
        }

        offcanvas.dispose();
    }
}

export function update(id, options, ref) {
    setup(id, options, ref);
}

export function show(id) {
    var element = getElement(id);
    var offcanvas = bootstrap.Offcanvas.getInstance(element);

    if (offcanvas != null && typeof offcanvas !== 'undefined') {
        offcanvas.show();
    }
}

export function hide(id) {
    var element = getElement(id);
    var offcanvas = bootstrap.Offcanvas.getInstance(element);

    if (offcanvas != null && typeof offcanvas !== 'undefined') {
        offcanvas.hide();
    }
}


function clearTimer(id) {
    if (window.bootstrap_offcanvas_timers) {
        if (window.bootstrap_offcanvas_timers[id]) {
            clearInterval(window.bootstrap_offcanvas_timers[id]);
            delete window.bootstrap_offcanvas_timers[id];
        }
    }
}

function setupTimer(id) {
    clearTimer(id);
    if (window.bootstrap_offcanvas_timers) {
        window.bootstrap_offcanvas_timers[id] = setInterval((id) => {

            var identifier = getIdentifier(id);
            if (!$('#' + identifier).is(":visible")) {
                destroy(id);
            }
        }, 100, id);
    }
}