/**
 * (c) by aheadware.com
 */

var app = app || {};
app.state = app.state || {};

app.state.GroupMemberManagement = function()
{
    var state = app.core.StateManager.createState( 'group-member-management' );

    state.onEnter = function( p )
    {
        let $content = app.core.View.getContent(),
            group = null,
            memberToEdit = null,
            members = [],
            membersActive = [],
            membersInactive = [],
            membersNotApproved = [],
            groupId = p.groupId,
            memberId = p.hasOwnProperty( 'memberId' ) ? p.memberId : null,
            activeTab = 'active';

        app.gui.PageLoader.show();

        app.core.Rpc.call(
            'Team',
            'getDetails',
            { teamId : groupId, includeEmails : true, includeMembers: true },
            function( res )
            {
                members.push( res );
                var member = null,
                    $memberContainer = null,
                    emails = res.emails ? res.emails : [];

                group = new app.model.Group( res.team );

                for ( var mi = 0; mi < res.members.length; mi++ )
                {
                    member = new app.model.Profile( res.members[ mi ] );
                    for ( var ei = 0; ei < emails.length; ei++ )
                    {
                        if ( member.getAccountId() == emails[ ei ].id )
                        {
                            member.setEmail( emails[ ei ].email );
                            member.setEmailValidated(emails[ ei ].is_validated == 1)
                            break;
                        }
                    }

                    if ( member.getId() == app.model.SessionUser.getProfileId() )
                    {
                        currentProfile = member;
                    }

                    switch (member.getGroupData(groupId).status) {
                        case 'active':
                            membersActive.push(member);
                            break;
                        case 'inactive':
                            membersInactive.push(member);
                            break;
                        case 'not_approved':
                            membersNotApproved.push(member);
                            break;
                    }
                }

                app.core.View.setContent(
                    app.core.View.getTemplate(
                        'group-member-management',
                        {
                            members : members,
                            membersActive: membersActive,
                            membersInactive: membersInactive,
                            membersNotApproved: membersNotApproved,
                            group : group,
                            groups : app.model.SessionUser.getAdminGroups(),
                            currentProfile : currentProfile,
                            activeTab: activeTab
                        } )
                );

                $content.find( '[data-id="select-group-id"]' ).first().change( function()
                {
                    app.core.Controller.redirect( '#/group/' + $(this).val() + '/membermanagement' );
                });

                $content.find( '[data-id="select-profil-id"]' ).first().change( function()
                {
                    app.core.Controller.redirect( '#/group/' + group.getId() + '/membermanagement/' + $(this).val() );
                });

                $content.on( 'click', '[data-type="member-link"]', function()
                {
                    var memberId = $(this).attr( 'data-member-id' );
                    app.core.Controller.redirect( '#/group/' + group.getId() + '/membermanagement/' + memberId );
                });
                $content.on( 'click', '[data-id="member-header"] .nav-tabs .nav-link', function()
                {
                    let searchInput = $content.find('[data-id="member-search-filter"]')
                    searchInput.val('');
                    searchInput.trigger('input');
                    $('[data-id="member-header"] .nav-tabs .nav-link').removeClass("active");
                    var content = $(this).data("content");
                    $(".group-members-content").removeClass("active");
                    $(this).addClass("active");
                    $("#" + content).addClass("active");
                });

                if ( memberId )
                {
                    $content.find( '[data-id="select-profil-id"]' ).first().val( memberId );
                    $content.find( '[data-id="select-profil-id"]' ).first().trigger( 'change' );
                    fnUpdateMemberToEdit( memberId )
                }

                $content.on('input', '[data-id="member-search-filter"]', function(e)
                {
                    var searchTerm = $(this).val().toLowerCase();

                    // Filter elements
                    $('table.table-profiles tbody tr').each(function() {
                        var $tr = $(this);
                        var userName = $tr.find('.align-middle > div').text().toLowerCase();

                        if (userName.includes(searchTerm) || searchTerm === '') {
                            $tr.show();
                        } else {
                            $tr.hide();
                        }
                    });
                });

                app.gui.PageLoader.hide();
            }
        );
    };

    return state;
};