Umi.Channels = (function() {
    const chans = new Map;
    let currentName = null;

    const onAdd = [],
        onRemove = [],
        onClear = [],
        onUpdate = [],
        onSwitch = [];

    return {
        OnAdd: onAdd,
        OnRemove: onRemove,
        OnClear: onClear,
        OnUpdate: onUpdate,
        OnSwitch: onSwitch,
        Add: function(channel) {
            const channelName = channel.getName();
            if(!chans.has(channelName)) {
                chans.set(channelName, channel);

                for(const i in onAdd)
                    onAdd[i](channel);
            }
        },
        Remove: function(channel) {
            const channelName = channel.getName();
            if(chans.has(channelName)) {
                chans.delete(channelName);

                for(const i in onRemove)
                    onRemove[i](channel);
            }
        },
        Clear: function() {
            chans.clear();

            for(const i in onClear)
                onClear[i]();
        },
        All: function() {
            return Array.from(chans.values());
        },
        Get: function(channelName) {
            channelName = channelName.toString();
            if(chans.has(channelName))
                return chans.get(channelName);
            return null;
        },
        Update: function(channelName, channel) {
            channelName = channelName.toString();
            chans.set(channelName, channel);

            for(const i in onUpdate)
                onUpdate[i](name, channel);
        },
        Current: function() {
            return currentName;
        },
        Switch: function(channelName) {
            const old = currentName;
            currentName = channelName;

            for(const i in onSwitch)
                onSwitch[i](old, channelName);
        },
    };
})();
