<?php
global $data;
$pageTitle='Usergroup: '.(isset($data['name'])) ? $data['name']: '';
include realpath(__DIR__).'/../_common/header.php'; ?>
<script type="text/javascript">
window.addEventListener('DOMContentLoaded',function(){

	
	ui.grid();
    const detailsBox = grid.box({
        classes: 'r1 c1 h3 w1',
        title: 'Details'
    });
    const frm = detailsBox.form({
        action: '/api/usergroup/' + data['id'],
    });
    const isSystem = data['issystem'] * 1;
    const isGroupAdmin = data['isgroupadmin'] * 1;
    frm.textField({ label:"Name", name:'name', value:data['name'], readonly:(isSystem || (!isAdmin && !isGroupAdmin)) });
	frm.textField({ label:"Description", name:'description', value:data['description'], readonly:(isSystem || (!isAdmin && !isGroupAdmin)) });
	frm.dropdown({ label:'Group visibility', name:'groupvisibility', value:data['groupvisibility'], readonly:(!isAdmin && !isGroupAdmin),
		options:[{ label:'Hidden',value:'hidden'}, {label:'Members only',value:'membersonly'}, {label:'Visible',value:'visible'}] });
	frm.dropdown({ label:'Membership visibility', name:'membershipvisibility', value:data['membershipvisibility'], readonly:(!isAdmin && !isGroupAdmin),
		options:[{ label:'Hidden',value:'hidden'}, {label:'Members only',value:'membersonly'}, {label:'Visible',value:'visible'}] });
// 	frm.dropdown({ label:'Joining the group', name:'joining', value:data['joining'], readonly:(!isAdmin &&!isSystem),
// 		options:[{ label:'Closed',value:'closed'}, {label:'Request',value:'request'}, {label:'Open',value:'open'}, {label:'Auto',value:'auto'}] });

if(data["name"]===groupNames["ADMINISTRATORS"]){
    frm.checkbox({ label:'Project creators', name:'cancreateprojects',value:1,readonly:true });
    frm.checkbox({ label:'Usergroup creators', name:'cancreateusergroups',value:1,readonly:true });
} else {
    frm.checkbox({ label:'Project creators', name:'cancreateprojects',readonly:!isAdmin });
    frm.checkbox({ label:'Usergroup creators', name:'cancreateusergroups',readonly:!isAdmin });
}

    const ts = grid.tabSet({classes: 'r1 c2 h3 w2'});
    const headers = ['Name', 'Group admin'];
    const cellTemplates = ['<a href="/user/{{id}}">{{fullname}}</a>', [Usergroup.writeIsGroupAdminCell, 'isgroupadmin']];
    if(isAdmin || 1===1*data.isgroupadmin){
		headers.push('<input type="button" onclick="Usergroup.startAddMember()" value="Add group members..." />');
		cellTemplates.push('<input type="button" onclick="Usergroup.removeMember(this)" value="Remove" />');
	}
	
	ts.tab({ 
		id:'members',
		label:'Members', 
		url:'/api/usergroup/'+data['id']+'/member', 
		headers:headers,
		cellTemplates:cellTemplates,
		failureHandler:Usergroup.membersTabOnFailure
	});
	ts.tab({ 
		id:'permissions', 
		label:'Permissions', 
		url:'/api/usergroup/'+data['id']+'/permission', 
		successHandler:Usergroup.writePermissions,
	 });

	
	
});

let Usergroup={

	membersTabOnFailure: function(transport){
        let out;
        if(404===1*transport.status){
			out='<p>This group has no members.</p><p><input type="button" onclick="Usergroup.startAddMember()" value="Add group members..." /></p>';
		} else if(transport.responseJSON && transport.responseJSON.error){
			out='<p>Could not get member list.</p><p>'+transport.responseJSON.error+'</p>';
		} else {
			out='<p>Could not get member list. The server said:</p><p>'+transport.responseText+'</p>';
		}
		document.getElementById("members_body").innerHTML=out;
	},
		
	writeIsGroupAdminCell: function(obj, field){
		if(1===1*obj["isadmin"]){
			return '<img src="/images/icons/yes.gif" alt="Yes'+'" title="(System-wide administrator)"/>'; //break to suppress "cannot resolve" warnings
		} else if(!isAdmin && 1!==1*data[field]){ //field is 'isgroupadmin' - warning suppression
			return ui.checkmark(obj,'isgroupadmin');
		} else {
			if(1===1*obj.isgroupadmin){
				return '<img src="/images/icons/btn_yes.gif" alt="Yes" id="gm'+obj.groupmembershipid+'" style="cursor:pointer" onclick="Usergroup.toggleIsGroupAdmin(this)" />';
			} else {
				return '<img src="/images/icons/btn_no.gif" alt="No" id="gm'+obj.groupmembershipid+'" style="cursor:pointer" onclick="Usergroup.toggleIsGroupAdmin(this)" />';
			}
		}
	},

	/**
	 * Remove the user from this usergroup.
	 * @param elem The "Remove" button
	 */
	removeMember: function(elem){
        const rowData = elem.closest("tr").rowData;
        if(!confirm('Remove '+rowData["fullname"]+' from group "'+data.name+'"?')){ return false;}
        const gmId = rowData.groupmembershipid;
        elem.closest("tr").classList.add("updating");
		new AjaxUtils.Request('/api/groupmembership/'+gmId, {
			method:'delete',
			parameters:{ csrfToken:csrfToken },
			onSuccess:function(transport){ Usergroup.removeMember_onSuccess(transport,elem); },
			onFailure:function(transport){ Usergroup.removeMember_onFailure(transport); }
		});
	},
	removeMember_onSuccess: function(transport,elem){
		if(!AjaxUtils.checkResponse(transport)){ return false; }
		elem.closest("tr").remove();
	},
	removeMember_onFailure: function(transport){
		AjaxUtils.checkResponse(transport);
	},


	/**
	 * Begin the "Add member" process by displaying a list of users who are not group members.
	 */
	startAddMember: function(){
		ui.modalBox({
			'url':'/api/usergroup/'+data.id+'/nonmember',
			'title':'Find users to add',
			'headers':['Name',''],
            'showFilters':[true,false],
			'cellTemplates':['{{fullname}}','<input type="button" onclick="Usergroup.addMember(this)" value="Add to group" />']
		});
	},

	/**
	 * Add the user to this usergroup. They will be added as a normal, non-group-admin, member.
	 * @param elem The "Add" button
	 */
	addMember: function(elem){
        const rowData = elem.closest("tr").rowData;
        elem.closest("tr").classList.add("updating");
		new AjaxUtils.Request('/api/groupmembership/', {
			method:'post',
			parameters:{ csrfToken:csrfToken, userid:rowData.id, usergroupid:data.id },
			onSuccess:function(transport){ Usergroup.addMember_onSuccess(transport,elem); },
			onFailure:function(transport){ Usergroup.addMember_onFailure(transport); }
		});
	},
	addMember_onSuccess: function(transport,elem){
		if(!AjaxUtils.checkResponse(transport)){ return false; }
		elem.closest("tr").remove();
		document.getElementById("members_body").refresh();
		if(!document.getElementById("modalBox").querySelector("tr.datarow")){
			ui.closeModalBox();
		}
	},
	addMember_onFailure: function(transport){
		AjaxUtils.checkResponse(transport);
	},
		
	/**
	 * Write the permissions table for this usergroup. Success handler for the Permissions tab.
	 * @param transport The XHR object
	 */
	writePermissions: function(transport){
	    return Permission.writePermissions(transport);
	},

	/**
	 * Promote a group member to group admin, or demote a group admin to a regular member.
	 * @param btn The toggle button/image.
	 */
	toggleIsGroupAdmin: function(btn){
        const tr = btn.closest("tr");
        if(tr.classList.contains("updating")){ return false; }
        const obj = tr.rowData;
        const newValue = (1 === 1 * obj.isgroupadmin) ? "0" : "1";
        tr.classList.add("updating");
		new AjaxUtils.Request("/api/groupmembership/"+obj.groupmembershipid,{
			method:"patch",
			parameters:{
				csrfToken:csrfToken,
				isgroupadmin:newValue,
			},
			onSuccess:Usergroup.toggleIsGroupAdmin_onSuccess,
			onFailure:Usergroup.toggleIsGroupAdmin_onFailure
		});
	},
	toggleIsGroupAdmin_onSuccess: function(transport){
		if(!AjaxUtils.checkResponse(transport)){ return false; }
        const updated = transport.responseJSON["updated"];
        const btn = document.getElementById("gm" + updated.id);
        const tr = btn.closest("tr");
        if(1===1*updated.isgroupadmin){
			btn.src=btn.src.replace("btn_no","btn_yes");
		} else {
			btn.src=btn.src.replace("btn_yes","btn_no");
		}
		tr.classList.remove("updating");
	},
	toggleIsGroupAdmin_onFailure: function(transport){
		AjaxUtils.checkResponse(transport);
	},
	
	/**
	 * Add or remove a group's permission on a project.
	 */
	togglePermission: function(evt){
		let btn=document.getElementById(evt.target);
		if(btn.closest("td").classList.contains("updating")){ return false; }
		btn.closest("td").classList.add("updating");
		if(btn.dataset.permissionid && btn.dataset.permissionid!==""){
			//delete the permission
			new AjaxUtils.Request("/api/permission/"+btn.dataset.permissionid,{
				method:"delete",
				postBody:"csrfToken="+csrfToken,
				onSuccess:function(transport){ Usergroup.togglePermission_onSuccess(transport,btn) },
				onFailure:function(transport){ Usergroup.togglePermission_onFailure(transport,btn) },
			});
		} else {
			//create the permission
			new AjaxUtils.Request("/api/permission",{
				method:"post",
				postBody:"csrfToken="+csrfToken+"&projectid="+btn.dataset.projectid+"&usergroupid="+btn.dataset.usergroupid+"&type="+btn.dataset.permissiontype,
				onSuccess:function(transport){ Usergroup.togglePermission_onSuccess(transport,btn) },
				onFailure:function(transport){ Usergroup.togglePermission_onFailure(transport,btn) },
			});
		}
	},
	togglePermission_onSuccess: function(transport,btn){
		btn.closest("td").classList.remove("updating");
		if(!transport.responseJSON || transport.responseJSON.error){
			return Usergroup.togglePermission_onFailure(transport,btn);
		}
		if(transport.responseJSON.created){ 
			btn.dataset.permissionid=transport.responseJSON.created.id;
			btn.src=btn.src.replace("no.gif","yes.gif");
		} else {
			btn.dataset.permissionid="";
			btn.src=btn.src.replace("yes.gif","no.gif");
		}
	},
	togglePermission_onFailure: function(transport,btn){
		btn.closest("td").classList.remove("updating");
		if(transport.responseJSON && transport.responseJSON.error){
			alert(transport.responseJSON.error);
		} else {
			alert(transport.responseText); 
		}
	},
	
} //end of Usergroup object

</script>
<?php include realpath(__DIR__).'/../_common/footer.php';