#include animate.js
#include common.js
#include settings.js
#include user.js
#include utility.js
#include ui/menus.js
#include ui/view.js

Umi.UI.Users = (function() {
    const toggleTimeouts = {};

    const toggleUser = function(id) {
        const prefix = 'user-' + id.toString(),
            userOptions = $i(prefix + '-options-wrapper'),
            closedClass = 'sidebar__user-options--hidden',
            isClosed = userOptions.classList.contains(closedClass);
        let update = null,
            start = null,
            end = null;

        if(prefix in toggleTimeouts) {
            clearTimeout(toggleTimeouts[prefix]);
            delete toggleTimeouts[prefix];
        }

        if(isClosed) {
            if(Umi.Settings.get('autoCloseUserContext'))
                toggleTimeouts[prefix] = setTimeout(function() {
                    if(Umi.Settings.get('autoCloseUserContext'))
                        toggleUser(id);
                }, 300000);

            start = function() {
                userOptions.classList.remove(closedClass);
            };
            update = function(t) {
                userOptions.style.maxHeight = (230 * t).toString() + 'px';
            };
        } else {
            end = function() {
                userOptions.classList.add(closedClass);
            };
            update = function(t) {
                userOptions.style.maxHeight = (230 - (230 * t)).toString() + 'px';
            };
        }

        MamiAnimate({
            duration: 500,
            easing: 'easeOutExpo',
            start: start,
            update: update,
            end: end,
        });
    };

    const createAction = function(text, events) {
        const elem = $e({ tag: 'li', attrs: { 'class': 'sidebar__user-option' }, child: text });
        for(const i in events)
            elem.addEventListener(i, events[i]);
        return elem;
    };

    return {
        Add: function(user) {
            const id = 'user-' + user.getId(),
                uBase = $e({ attrs: { 'class': 'sidebar__user', id: id } }),
                uDetails = $e({ attrs: { 'class': 'sidebar__user-details', id: id + '-details' } }),
                uAvatar = $e({ attrs: { 'class': 'sidebar__user-avatar', id: id + '-avatar' } }),
                uName = $e({ attrs: { 'class': 'sidebar__user-name', id: id + '-name' } }),
                uOptions = $e({ tag: 'ul', attrs: { 'class': 'sidebar__user-options', id: id + '-options' } });

            uDetails.addEventListener('click', function() {
                toggleUser(user.getId());
            }.bind(this));

            const profileUrl = futami.get('profile');
            if (profileUrl !== null || profileUrl.length > 1) {
                uOptions.appendChild(createAction('View profile', {
                    'click': function() {
                        window.open(profileUrl.replace('{user:id}', user.getId()), '_blank');
                    }
                }));
            }
            if (Umi.User.isCurrentUser(user)) {
                uOptions.appendChild(createAction('Describe action', {
                    'click': function() {
                        Umi.UI.View.SetText('/me ');
                    }
                }));
                if (user.canSetNickName()) {
                    uOptions.appendChild(createAction('Set nickname', {
                        'click': function() {
                            Umi.UI.View.SetText('/nick ');
                        }
                    }));
                }
                if (user.canBan()) {
                    uOptions.appendChild(createAction('View bans', {
                        'click': function() {
                            Umi.UI.View.SetText('/bans');
                        }
                    }));
                    uOptions.appendChild(createAction('Kick Fucking Everyone', {
                        'click': function() {
                            if(confirm('You are about to detonate the fucking bomb. Are you sure?')) {
                                const targets = Umi.Users.All();
                                for(const target of targets)
                                    Umi.Server.sendMessage('/kick ' + target.getName());
                            }
                        }
                    }));
                }
            }
            else {
                /*uOptions.appendChild(createAction('Send PM', {
                    'click': function() {
                        Umi.UI.View.SetText('/msg ' + user.getName() + ' ');
                    }
                }));*/
                if (Umi.User.getCurrentUser().canBan()) {
                    uOptions.appendChild(createAction('Kick', {
                        'click': function() {
                            Umi.UI.View.SetText('/kick ' + user.getName());
                        }
                    }));
                    uOptions.appendChild(createAction('View IP', {
                        'click': function() {
                            Umi.UI.View.SetText('/ip ' + user.getName());
                        }
                    }));
                }
            }
            uName.style.color = user.getColour();
            uBase.style.backgroundColor = user.getColour() === 'inherit' ? '#fff' : user.getColour();

            let afkText = '',
                sbUserName = user.getName();
            
            if(sbUserName.indexOf('<') === 0) {
                afkText = sbUserName.substring(1, sbUserName.indexOf('>'));
                sbUserName = sbUserName.substring(afkText.length + 3);
            }

            const isAFK = afkText.length > 0;
            if(isAFK)
                uName.appendChild($e({ attrs: { 'class': 'user-sidebar-afk' }, child: afkText }));

            if(sbUserName.length > 16 || Umi.Settings.get('marqueeAllNames')) {
                uName.appendChild($e({
                    tag: 'marquee',
                    attrs: {
                        style: {
                            width: '180px',
                            overflow: 'hidden',
                        },
                    },
                    child: sbUserName,
                }));
            } else {
                uName.appendChild($t(sbUserName));
            }

            const avatarUrl = futami.get('avatar');
            if(avatarUrl !== null && avatarUrl.length > 1) {
                uAvatar.style.backgroundImage = 'url({0})'.replace('{0}', avatarUrl.replace('{user:id}', user.getId()).replace('{resolution}', '80').replace('{user:avatar_change}', user.getAvatarTime().toString()));
                uDetails.appendChild(uAvatar);
            }

            uDetails.appendChild(uName);
            uBase.appendChild(uDetails);
            uBase.appendChild($e({child: uOptions, attrs: { id: id + '-options-wrapper', className: 'sidebar__user-options-wrapper sidebar__user-options--hidden', }}));
            Umi.UI.Menus.Get('users').appendChild(uBase);
        },
        Update: function(user) {
            const uBase = $i('user-' + user.getId()),
                uAvatar = $i('user-' + user.getId() + '-avatar'),
                uName = $i('user-' + user.getId() + '-name');
            uName.style.color = user.getColour();
            uBase.style.backgroundColor = user.getColour() === 'inherit' ? '#fff' : user.getColour();
            uName.textContent = '';

            let afkText = '',
                sbUserName = user.getName();

            const avatarUrl = futami.get('avatar');
            if(avatarUrl !== null && avatarUrl.length > 1)
                uAvatar.style.backgroundImage = 'url({0})'.replace('{0}', avatarUrl.replace('{user:id}', user.getId()).replace('{resolution}', '80').replace('{user:avatar_change}', user.getAvatarTime().toString()));

            if(sbUserName.indexOf('<') === 0) {
                afkText = sbUserName.substring(1, sbUserName.indexOf('>'));
                sbUserName = sbUserName.substring(afkText.length + 3);
            }

            const isAFK = afkText.length > 0;
            if(isAFK)
                uName.appendChild($e({ attrs: { 'class': 'user-sidebar-afk' }, child: afkText }));

            if(sbUserName.length > 16 || Umi.Settings.get('marqueeAllNames')) {
                uName.appendChild($e({
                    tag: 'marquee',
                    attrs: {
                        style: {
                            width: '180px',
                            overflow: 'hidden',
                        },
                    },
                    child: sbUserName,
                }));
            } else
                uName.appendChild($t(sbUserName));
        },
        Remove: function(user) {
            $ri('user-' + user.getId());
        },
        RemoveAll: function() {
            Umi.UI.Menus.Get('users').innerHTML = '';
        },
        CreateAction: createAction,
        ToggleUser: toggleUser,
    };
})();
