(function (context) {

    /**
     * Javascript wrappers for the REST API
     */

    "use strict";

    var AuthorizedEventStorage = {}
    context.JK = context.JK || {};
    context.JK.AuthorizedEventStorage = AuthorizedEventStorage

    var key = 'authorized_events'

    AuthorizedEventStorage.storeAuthorizedEvent = (authorizedEvent) => {
        console.log("storing authorized event", authorizedEvent)
        var events = fetchFromStorage()
        if(!events) {
            events = {}
        }
        if(!events.list) {
            events.list = {}
        }

        if(!authorizedEvent.event_id) {
            console.error("no event_id on new event", authorizedEvent)
            alert("Unable to store order (no event_id)! Please contact support@jamkazam.com.")
            return
        }
        if(!authorizedEvent.order_id) {
            console.error("no order_id on new event", authorizedEvent)
            alert("Unable to store order (no order_id)! Please contact support@jamkazam.com.")
            return
        }

        events.list[authorizedEvent.event_id] = authorizedEvent

        try {
            window.localStorage.setItem(key, JSON.stringify(events) )
        }
        catch(e) {
            console.error("can't update localStorage")
            alert("Could not update local storage ith order.\nPlease try a different browser.  Please do not use incognito mode.")
        }

    }

    AuthorizedEventStorage.locateEvent = (eventId) => {
        var events = fetchFromStorage()
        if(events && events.list) {
            return events.list[eventId]
        }
        else {
            console.log("no events found in storage")
            return null
        }
    }

    AuthorizedEventStorage.listAuthorizedEvents = () => {
        var events = fetchFromStorage()
        if(events) {
            return events.list
        }
        else {
            return {}
        }
    }

    function fetchFromStorage() {
        var events = window.localStorage.getItem(key)
        if(events){
            try {
                return JSON.parse(events)
            }
            catch(e){
                console.log("events not parseable", events)
                return null;
            }
        }
    }
})(window);
