#include animate.js
#include common.js
#include users.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();
        const userOptions = $i(prefix + '-options-wrapper');
        const closedClass = 'sidebar__user-options--hidden';
        const isClosed = userOptions.classList.contains(closedClass);
        let start, update, end, height;

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

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

            start = () => {
                userOptions.classList.remove(closedClass);
                const curHeight = userOptions.style.height;
                userOptions.style.height = null;
                height = userOptions.clientHeight;
                userOptions.style.height = curHeight;
            };
            update = function(t) {
                userOptions.style.height = `${height * t}px`;
            };
            end = () => {
                userOptions.style.height = null;
            };
        } else {
            start = () => {
                height = userOptions.clientHeight;
            };
            update = t => {
                userOptions.style.height = `${height - (height * t)}px`;
            };
            end = () => {
                userOptions.style.height = '0';
                userOptions.classList.add(closedClass);
            };
        }

        // todo: actually make cancellable
        MamiAnimate({
            duration: 500,
            easing: 'outExpo',
            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.id;
            const uBase = $e({ attrs: { 'class': 'sidebar__user', id: id } });
            const uDetails = $e({ attrs: { 'class': 'sidebar__user-details', id: id + '-details' } });
            const uAvatar = $e({ attrs: { 'class': 'sidebar__user-avatar', id: id + '-avatar' } });
            const uName = $e({ attrs: { 'class': 'sidebar__user-name', id: id + '-name' } });
            const uOptions = $e({ tag: 'ul', attrs: { 'class': 'sidebar__user-options', id: id + '-options' } });

            uDetails.addEventListener('click', function() {
                toggleUser(user.id);
            }.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.id), '_blank');
                    }
                }));
            }
            if (Umi.User.isCurrentUser(user)) {
                uOptions.appendChild(createAction('Describe action', {
                    'click': function() {
                        Umi.UI.View.SetText('/me ');
                    }
                }));
                if (user.perms.canSetNick) {
                    uOptions.appendChild(createAction('Set nickname', {
                        'click': function() {
                            Umi.UI.View.SetText('/nick ');
                        }
                    }));
                }
                if (user.perms.canKick) {
                    uOptions.appendChild(createAction('View bans', {
                        'click': function() {
                            Umi.UI.View.SetText('/bans');
                        }
                    }));
                    uOptions.appendChild(createAction('Kick Fucking Everyone', {
                        'click': function() {
                            mami.msgbox.show({
                                body: ['You are about to detonate the fucking bomb.', 'Are you sure?'],
                                yes: { text: 'FUCK IT, WE BALL' },
                                no: { text: 'nah' },
                            }).then(() => {
                                const targets = Umi.Users.All().reverse();
                                for(const target of targets) // this shouldn't call it like this but will have to leave it for now
                                    Umi.Server.sendMessage('/kick ' + target.name);
                            }).catch(() => {});
                        }
                    }));
                }
            }
            else {
                /*uOptions.appendChild(createAction('Send PM', {
                    'click': function() {
                        Umi.UI.View.SetText('/msg ' + user.name + ' ');
                    }
                }));*/
                if (Umi.User.getCurrentUser().perms.canKick) {
                    uOptions.appendChild(createAction('Kick', {
                        'click': function() {
                            Umi.UI.View.SetText('/kick ' + user.name);
                        }
                    }));
                    uOptions.appendChild(createAction('View IP', {
                        'click': function() {
                            Umi.UI.View.SetText('/ip ' + user.name);
                        }
                    }));
                }
            }
            uName.style.color = user.colour;
            uBase.style.backgroundColor = user.colour === 'inherit' ? '#fff' : user.colour;

            if(user.status.isAway)
                uName.appendChild($e({ attrs: { 'class': 'user-sidebar-afk' }, child: user.status.message }));

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

            const avatarUrl = futami.get('avatar');
            if(avatarUrl !== null && avatarUrl.length > 1) {
                uAvatar.style.backgroundImage = 'url({0})'.replace('{0}', avatarUrl.replace('{user:id}', user.id).replace('{resolution}', '80').replace('{user:avatar_change}', user.avatarChangeTime));
                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.id);
            const uAvatar = $i('user-' + user.id + '-avatar');
            const uName = $i('user-' + user.id + '-name');
            uName.style.color = user.colour;
            uBase.style.backgroundColor = user.colour === 'inherit' ? '#fff' : user.colour;
            uName.textContent = '';

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

            if(user.status.isAway)
                uName.appendChild($e({ attrs: { 'class': 'user-sidebar-afk' }, child: user.status.message }));

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