#include channels.js
#include messages.js
#include utility.js
#include ui/menus.js

Umi.UI.Channels = (function() {
    const sidebarChannel = 'sidebar__channel';
    const sidebarChannelCurrent = 'sidebar__channel--current';
    const sidebarChannelUnread = 'sidebar__channel--unread';

    const markUnread = function(id, mode) {
        if(!id)
            return;

        const channel = $i('channel-' + id.toLowerCase().replace(' ', '-'));
        if(!channel)
            return;

        if(!mode && !channel.classList.contains(sidebarChannelCurrent) && channel.classList.contains(sidebarChannelUnread))
            channel.classList.add(sidebarChannelUnread);
        else if (mode && channel.classList.contains(sidebarChannelUnread))
            channel.classList.remove(sidebarChannelUnread);
    };

    return {
        Add: function(channel) {
            const id = 'channel-' + channel.name.toLowerCase().replace(' ', '-'),
                cBase = $e({ attrs: { 'class': sidebarChannel, id: id } }),
                cDetails = $e({ attrs: { 'class': sidebarChannel + '-details' } }),
                cName = $e({ attrs: { 'class': sidebarChannel + '-name' } });

            cBase.setAttribute('data-umi-channel', channel.name);
            cBase.setAttribute('onclick', 'Umi.UI.Channels.Switch(this.getAttribute(\'data-umi-channel\'))');

            cName.appendChild($t(channel.name));
            cDetails.appendChild(cName);
            cBase.appendChild(cDetails);

            Umi.UI.Menus.Get('channels').appendChild(cBase);
        },
        Update: function(id, channel) {
            const cBase = $i('channel-' + id.toLowerCase().replace(' ', '-'));
            cBase.id = channel.name.toLowerCase().replace(' ', '-');
            cBase.innerText = channel.name;
        },
        Remove: function(channel) {
            $ri('channel-' + channel.name.toLowerCase().replace(' ', '-'));
        },
        RemoveAll: function() {
            Umi.UI.Menus.Get('channels').innerHTML = '';
        },
        Reload: function(initial) {
            const current = Umi.Channels.Current(),
                channel = $i('channel-' + current.name.toLowerCase().replace(' ', '-')),
                prev = $c(sidebarChannelCurrent)[0];

            if((typeof prev).toLowerCase() !== 'undefined')
                prev.classList.remove(sidebarChannelCurrent);

            channel.classList.add(sidebarChannelCurrent);

            if(initial)
                return;

            Umi.UI.Messages.RemoveAll();
            const channelMsgs = Umi.Messages.All(current.name);
            for(const channelMsg of channelMsgs)
                Umi.UI.Messages.Add(channelMsg);
        },
        Switch: function(channelName) {
            markUnread(channelName, true);
            Umi.Channels.Switch(Umi.Channels.Get(channelName));
        },
        Unread: markUnread,
    };
})();
