(function () {

    if( !semusiCommon.isAdmin() ){
		window.location =  "/dashboard";
	}
    if(isAdmin() || isManager()) {
        document.getElementById('add_btn').style.display = 'block';
    }
    else{
        document.getElementById('add_btn').style.display = 'none';
    }
        //Check string is valid JSON before parse  
        function isJson(str) {
            try {
                JSON.parse(str);
            } catch (e) {
                  return false;
            }
              return true;
          }  
        
          //Check isGlobal Admin
          function isGlobalAdmin() {
              if(semusiCommon.isGlobalAdmin) {
                  return true;
              }
              else{
                  return false;
              }
        
          }
        
            //Check isAdmin validator
            function isAdmin() {
                let role = isJson(localStorage.getItem('user_role'))?JSON.parse(localStorage.getItem('user_role')):localStorage.getItem('user_role');
                if(role && role == 'admin') {		
                    return true;
                }else{
                    return false;
                }
                
            }
        
            //Check isManager validator
            function isManager() {
                let role = isJson(localStorage.getItem('user_role'))?JSON.parse(localStorage.getItem('user_role')):localStorage.getItem('user_role');
                if(role && role == 'manager') {		
                    return true;
                }else{
                    return false;
                }
                
            }
        

    function loadPage() {

            
            getUsers();


            var unblockUserNew = function(data, type, full, meta){
        
                var unblockBtn ;
                    if(semusiCommon.isGlobalAdmin || isAdmin()) {
                        resetBtn = `<button title="unblock" value=${full.email} type="button" class="unblockUser btn btn-success m-r-5 m-b-5" id=${full._id}><i class="fa fa-unlock">	</i>	</button>`
                     }else{	
                        resetBtn =  '<b>   </b>';
                          }
                return resetBtn	  
            }
        
            var resetPassword = function(data, type, full, meta){
                var resetBtn ;
                if(semusiCommon.isGlobalAdmin || isAdmin()) {
                    resetBtn = `<button title="Reset" value=${full.email} type="button" class="resetUserPassword btn btn-warning m-r-5 m-b-5" id=${full._id}><i class="fa fa-key">	</i>	</button>`
                 }else{	
                    resetBtn =  '<b>   </b>';
                      }
                return resetBtn	  
            }
            var simple_checkbox = function ( data, type, full, meta )
            {
        
                if(semusiCommon.isGlobalAdmin || isAdmin()) {
                    let is_checked = ''
                    let label = "Approved"
                    if(data && data .includes(semusiCommon.ACTIVE_APP_ID)){
                            is_checked = "checked"
                            label = "Not&nbsp;Approved"
                         }
                            return  '<input type="checkbox" '+is_checked+' name="my-checkbox" id='+full._id+' data-off-text="Not&nbsp;Approved" data-on-text="Approved"  data-on-color="success" data-off-color="danger" data-size="normal" data-label-text="'+label+'">';			 			 
                 }else{	
        
                            return '<b>   </b>'
                      }
        
            }
            function check(e){
                var name = $(e).attr('id');
        
                $.ajax({
                type:"GET",
               url:semusiCommon.API_PARTS.users.w + '/updateApproved',
                data:{
                    args:JSON.stringify({
                        user_id:name,
                        isapproved:$('input[id='+name+']').bootstrapSwitch('state'),
                        modified_by:"<%= member.user_id%>",
                        email:$('label[id=lbl'+name+']').text()
                       }),
                    api_key: semusiCommon.getActiveUser.api_key,
                    app_id: semusiCommon.ACTIVE_APP_ID,
                    uniqueNumber : semusiCommon.randomNumber(),
                },
                
                success:function (data) {
        
                }
                });
            }
        
            

            function changeRole(id, value) {
        
        
        if(confirm("Are you sure want to change this role ?")){
            //IF User isAdmin 
        
            if(isAdmin() || isManager()){
            //Update Role of Users
            var userId = id;
            var role = value;
            let modified_by = "<%= member.user_id%>";
            let appid = JSON.parse(localStorage.getItem('semusi_active_app'));
        
            $.ajax({
                    type:"GET",
                    url:semusiCommon.API_PARTS.users.r + '/updateRole',
                    data:{
                        api_key: semusiCommon.getActiveUser.api_key,
                        uniqueNumber : semusiCommon.randomNumber(),
                        args: JSON.stringify({
                            modified_by: modified_by,
                            userId: userId,
                            email:  "<%= member.email %>",
                            appid : appid,
                            role: role
                        })
                    },
                    dataType:"json",
                    success:function (data) {
                    
                        if(data) {
         
                            showMessagesucess(`User Role Updated`);
                            $("#messagesucess").delay(3000).fadeOut(300);
                            $("#message").delay(3000).fadeOut(300); 
                            window.location.reload()
                        } else {
                            showMessage("Something went wrong");
                            $("#message").delay(3000).fadeOut(300); 
                            return;
                        }
                    }
        
                    });
        
                }else{
                    showMessage("You are not authorized to change role");
                    $("#message").delay(3000).fadeOut(300); 
                    return;
                }
        
            }
        
            }
        
            
            function unblockUser (e, userEmailId){
                let userId = $(e).attr('id');
                let modified_by = "<%= member.user_id%>";
                $.ajax({
                        type:"GET",
                        url:semusiCommon.API_PARTS.users.r + '/unblockUser',
                        data:{
                            api_key: semusiCommon.getActiveUser.api_key,
                            app_id: semusiCommon.ACTIVE_APP_ID,
                            uniqueNumber : semusiCommon.randomNumber(),
                            args: JSON.stringify({
                                modified_by: modified_by,
                                userId: userId,
                                email:  userEmailId,
        
                            })
                        },
                        dataType:"json",
                        success:function (data) {
        
                         if(data =="Unblocked") {
                                    showMessagesucess(`User with id `+userEmailId+` has been unblocked`)
                                    $("#messagesucess").delay(3000).fadeOut(300);
                                    $("#message").delay(3000).fadeOut(300); 
                         }
                        }
                    });
            }
        
            function resetUserPassword(e,userEmailId){
                let userId = e;
                let modified_by = "<%= member.user_id%>";
                var newGENerated = semusiCommon.generateRandomAlphanumericString(10);
                newGENerated = newGENerated.toString();
                let newHashGENerated = newGENerated;
                if ("<%= t %>"== 'sha256'){
                    newHashGENerated = sha256(newHashGENerated);
                }
                    $.ajax({
                        type:"GET",
                        url:semusiCommon.API_PARTS.users.r + '/resetUserPassword',
                        data:{
                            api_key: semusiCommon.getActiveUser.api_key,
                            app_id: semusiCommon.ACTIVE_APP_ID,
                            uniqueNumber : semusiCommon.randomNumber(),
                            args: JSON.stringify({
                                modified_by: modified_by,
                                userId: userId,
                                field: newHashGENerated,
                                appid : JSON.parse(localStorage.getItem('semusi_active_app')),
                                email:  userEmailId,
        
                            })
                        },
                        dataType:"json",
                        success:function (data) {
        
                         if(data) {
                            (data=="Email Sent") ? showMessagesucess(`New Password sent to the registered email User`) : showMessagesucess(`Password of the user reset, Copy the password for future use`);
                                    $("#messagesucess").delay(3000).fadeOut(300);
                                    $("#message").delay(3000).fadeOut(300); 
                                    $('#passwordInput').val(newGENerated);
                                    $('#passwordPopupModel').modal('show');
                         }
                        }
                    });
            }
            function deleteUser(e){
                if(isGlobalAdmin()){
                    if(confirm('Are you sure want to delete this user permenantly?')){
                        let userId = $(e).attr('id');
                        let modified_by = "<%= member.user_id%>";
        
                        $.ajax({
                        type:"GET",
                        url:semusiCommon.API_PARTS.users.r + '/deleteUserpermenantly',
                        data:{
                            api_key: semusiCommon.getActiveUser.api_key,
                            app_id: semusiCommon.ACTIVE_APP_ID,
                            uniqueNumber : semusiCommon.randomNumber(),
                            args: JSON.stringify({
                                modified_by: modified_by,
                                userId: userId,
                                appid : JSON.parse(localStorage.getItem('semusi_active_app')),
                            })
                        },
                        dataType:"json",
                        success:function (data) {
                         if(data) {
                            showMessagesucess(`User has been Deleted`);
                            $("#messagesucess").delay(3000).fadeOut(300);
                            $("#message").delay(3000).fadeOut(300); 
                            window.location.reload()
                         }
                        }
                    });
                    }
                }else{
                    return	
                }
            }
            function deleteRole(e) {
                //IF User isAdmin 
        
                if(isAdmin()){
                if(confirm('Are you sure want to invoke role from this user ?')){
                let userId = $(e).attr('id');
                let modified_by = "<%= member.user_id%>";
                $.ajax({
                        type:"GET",
                        url:semusiCommon.API_PARTS.users.r + '/deleteUsersRole',
                        data:{
                            api_key: semusiCommon.getActiveUser.api_key,
                            app_id: semusiCommon.ACTIVE_APP_ID,
                            uniqueNumber : semusiCommon.randomNumber(),
                            args: JSON.stringify({
                                modified_by: modified_by,
                                userId: userId,
                                appid : JSON.parse(localStorage.getItem('semusi_active_app')),
                            })
                        },
                        dataType:"json",
                        success:function (data) {
                         if(data) {
                            showMessagesucess(`User Role Invoked`);
                            $("#messagesucess").delay(3000).fadeOut(300);
                            $("#message").delay(3000).fadeOut(300); 
                            window.location.reload()
                         }
                        }
                    });
        
                }else{
                    return;
                }
            }
        
                else{
                    showMessage("You are not authorized to change role");
                    $("#message").delay(3000).fadeOut(300); 
                    return;
                }
        
        
            }
        
            var simple_labelemail = function ( data, type, full, meta )
            {
                    return '<label value='+data+' id=lbl'+full._id+' > '+data+'</label>';
            }
            var hidden_label= function ( data, type, full, meta )
            {	
              if(isGlobalAdmin()){
                var status ="Approved";
        
                    if(data!=true)
                    {
                      status="Rejected"
                    }
                return '<label value='+status+'  > '+status+'</label>';
              }
              return '<b>   </b>';
            }
            var display_date = function (data, type, full, meta){
                if(data && data!==""){
                    return '<label value="'+ data +'">'+semusiCommon.getDateFromEpoch(data,false ,true) +'</label>';
                }
                else{
                    return '<label value="">   - </label>';
                }
        
            }
            var display_role = function (data, type, full, meta){ 
               let role= "NO ROLE YET ";
               let appid = JSON.parse(localStorage.getItem('semusi_active_app'));
        
            if(full.user_role){
               Object.keys(data).forEach(ele =>{
                data[ele].forEach(ele2 =>{
                    if(ele2 == appid){
                        let firstChar = ele.charAt([0]).toUpperCase();
                        role = ele.replace(ele[0],firstChar);
                        return;
                    }
                })
                return;
                })
                }
              return('<label value='+role+' id=lbl'+full._id+' > '+role+'</label>');
            }
            var change_role = function(data, type, full, meta){ 
                let select;
                const app_id = JSON.parse(localStorage.getItem('semusi_active_app'))
                if(isAdmin()) {
                  if(full.user_role){
                        if( (full.user_role.admin &&       Array.isArray(full.user_role.admin) && full.user_role.admin.includes(app_id) ) ||
                            (full.user_role.manager &&    Array.isArray(full.user_role.manager) && full.user_role.manager.includes(app_id) ) ||
                            (full.user_role.marketer &&  Array.isArray(full.user_role.marketer) && full.user_role.marketer.includes(app_id) )
                        ){
                        select = `<select id=${full._id} value="${full._id}" class="changeRole form-control">
                                <option value="" hidden selected>Select Role</option>
                                <option value="admin">Admin</option>
                                <option value="marketer">Marketer</option>
                                <option value="manager">Manager</option>
                            </select>`			
                    }else{
                        select =`<a style="height:35px; float: right;" id="add_btn" class="addUsers btn btn-primary btn-sm m-r-5 m-b-5"
                            type="button" >
                            Add User to this app
                        </a>`
                    } 
                 }else{
                    select =`<a style="height:35px; float: right;" id="add_btn" class="addUsers btn btn-primary btn-sm m-r-5 m-b-5"
                            type="button" >
                            Add User to this app
                        </a>`
                 }
                }
                else{
                    select = `<b>   </b>`
                }
                
                return  select;
            }
        
            var del_role = function(data, type, full, meta) {
                let delbtn;
                if(isAdmin()) {
                    delbtn = `
                    <button title="Delete role from this app" type="button" 
                    class="deleteRole btn btn-info m-r-5 m-b-5" id=${full._id}><i class="fa fa-minus-circle">
                    </i>
                    </button>
                `;
                }
                else{
                    delbtn = `<b>   </b>`;
                }
                
        
                return delbtn;
            }
            var del_user = function(data,type,full,meta){
                if(isGlobalAdmin()){
                    return `
                    <button title="Delete user from this app" type="button" 
                    class="deleteUser btn btn-danger m-r-5 m-b-5" id=${full._id}><i class="fa fa-trash">
                    </i>
                    </button>
                `
                }else{
                    return `<b>   </b>`
                }
            }
            function getUsers()
            {
                const app_id = localStorage.getItem('semusi_active_app');
                        $.ajax({
                        type:"GET",
                        url:semusiCommon.API_PARTS.users.r + '/allUsers',
                        data:{
                            api_key: semusiCommon.getActiveUser.api_key,
                            app_id: semusiCommon.ACTIVE_APP_ID,
                            uniqueNumber : semusiCommon.randomNumber(),
                            appid: app_id,
                            args: JSON.stringify({
                                appid: app_id,
                            })
                        },
                        dataType:"json",
                        success:function (data) {
                
                        // get site config
                        const siteConfig = data.siteConfig;
                        var oTable =  $('#users').dataTable({
                            
                        "bProcessing": true,
                        "aaSorting": [],
                        "dom":' <"search"f><"top"l>rt<"bottom"ip><"clear">', // Allign Search
                        "aaData": data.members,// <-- Data source
                        "fnDrawCallback": function( oSettings ) {
                                 $("[name='my-checkbox']").bootstrapSwitch();
                                 $('.bootstrap-switch-label').css("background","#f5f5f5");
                                 $(".bootstrap-switch-label").css("font-size","12px");
                                 $(".addUsers").off().on('click', function(){
                                      addUser();
                                  });
                                  $(".deleteRole").off().on('click', function(){
                                      deleteRole($(this));
                                  });
                                  $(".deleteUser").off().on('click', function(){
                                    deleteUser($(this));
                                  });
                                  $(".changeRole").off().on('change', function(){
                                            changeRole($(this).attr("id"),$(this).val());
                                  });
                                  $('.resetUserPassword').off().on('click', function(){
                                      resetUserPassword($(this).attr("id"),$(this).val());
                                  });
                                  $('.unblockUser').off().on('click', function(){
                                      unblockUser($(this).attr("id"),$(this).val());
                                  });
                                 $("[name='my-checkbox']").on('switchChange.bootstrapSwitch', function (event, state) {
                                     if(state){
                                    var text=$(this).bootstrapSwitch('offText');
                                    check($(this));
                                    $(this).bootstrapSwitch('labelText',text);
        
                                }
                                else{
                                    var text=$(this).bootstrapSwitch('onText');
                                    check($(this));
                                    $(this).bootstrapSwitch('labelText',text);
                                }
                                 });
                        },
        
                         "aoColumns": [
                              { "mData": 'email',"render": simple_labelemail ,"sWidth": "15%" ,"bVisible":true,"bSortable": true},
                              { "mData": 'createdOn' ,"render": display_date,"sWidth": "15%" ,"bVisible":true},
                              { "mData": 'modifiedOn' ,"render": display_date,"sWidth": "15%" ,"bVisible":true },
                              { "mData": 'user_role' ,"render": display_role,"sWidth": "15%" ,"bVisible":true, "defaultContent": ""},
                              { "mData": 'user_role' ,"render": change_role,"sWidth": "15%" ,"bVisible":true, "defaultContent": ""},
                              { "mData": 'user_role' ,"render": del_role,"sWidth": "5%" ,"bVisible":true, "defaultContent": ""},
                              { "mData": 'approvedAppids',"render": simple_checkbox,"sWidth": "20%" , "bVisible" :true}, // This is  Approved /Unapproaved checkbox 
                              { "mData": 'approvedAppids' ,"render": hidden_label,"sWidth": "10%" ,"bVisible":false },   //  This is Approved /Unapproaved label 
                              { "mData": 'isapproved' ,"render": resetPassword,"sWidth": "5%" ,"bVisible":true },
                              { "mData": 'isapproved' ,"render": unblockUserNew,"sWidth": "55%" ,"bVisible":true },
                              { "mData": 'user_role' ,"render": del_user,"sWidth": "5%" ,"bVisible":true, "defaultContent": ""},
        
                            ]
                        });
                        var dataTable = $('#users').DataTable();
                        // In case of Ad based Authentication 
                        if (siteConfig && siteConfig.sso_type =="ad") {
                            // rename email column to Ad Id 
                            $("#emailOrAdIdHeader").text("SSo Id");
                            dataTable.column(8).visible(false) 		// hiding the reset Password Button
                        } else {
                            // setting column to email 
                            $("#emailOrAdIdHeader").text("Email");
                            dataTable.column(8).visible(true)     // showing the reset Password Button
                        }
        
                        if(!isGlobalAdmin() && isAdmin()){
                            dataTable.column(10).visible(false); //for App Admin don't show the delete user button
                        }
                        if(!isAdmin()){
                            for(i=5;i<=11;i++){
                                dataTable.column(i).visible(false); //for Manager/Marketer 
                            }
                        }
        
                            $("[name='my-checkbox']").bootstrapSwitch();
                        }});
            }
        
        
    }
    window.onload = loadPage;
}());
