/*
Licensed Materials - Property of IBM
5900-A2A
© Copyright IBM Corporation 2020. All Rights Reserved.
This sample program is provided AS IS and may be used, executed, copied and modified without royalty payment by customer
(a) for its own instruction and study, (b) in order to develop applications designed to run with an IBM product,
either for customer's own internal use or for redistribution by customer, as part of such an application, in customer's
own products.
*/


package accessmanagement;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import model.Group;
import model.Member;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpDelete;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import services.ConfigServices;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class ManageGroups {
	
	private static String csrf_token;
	
	public static void main(String[] args) {
		generateCSRF();
		
	}
	
	public static void generateCSRF() {

	String url = ConfigServices.getProperty("Url") + ConfigServices.getProperty("CSRFTokenEndpoint");

	String data =  "{\"requested_lifetime\":7200}";

	HttpPost post = new HttpPost(url);
	try {
		
		if (data != null) {
			post.setEntity(new StringEntity(data));
			post.addHeader("Authorization", ConfigServices.getProperty("AuthorizationBearerToken"));
			post.addHeader("Content-Type", "application/json");
		}
		ObjectMapper mapper = new ObjectMapper();
		
		CloseableHttpClient httpClient = HttpClients.createDefault();
		HttpResponse response = httpClient.execute(post);
		
		Map<String,Object> map = mapper.readValue(response.getEntity().getContent(), Map.class);


		csrf_token = (String) map.get("csrf_token");
		
	} catch (Exception e) {
		System.out.println(e);
	} finally {
		post.abort();
	}

	}
	
	void createGroups(List<Group> groups) {
		for(Group group : groups) {
			createGroup(group);
		}
	}
	
	
	void createGroup(Group group) {
			
		ObjectMapper mapper = new ObjectMapper();
		
		String data = "";
		try {
			data = mapper.writeValueAsString(group);
		} catch (JsonProcessingException e1) {
			e1.printStackTrace();
		}
		
		generateCSRF();

		String url = ConfigServices.getProperty("Url") + ConfigServices.getProperty("GroupEndpoint");

		HttpPost post = new HttpPost(url);
		try {

			
			if (data != null) {
				post.setEntity(new StringEntity(data));
				post.addHeader("Authorization", ConfigServices.getProperty("AuthorizationBearerToken"));
				post.addHeader("Content-Type", "application/json");
				post.addHeader("IBM-CSRF-TOKEN", csrf_token);
			}
			
			CloseableHttpClient httpClient = HttpClients.createDefault();
			HttpResponse response = httpClient.execute(post);

			Map<String,Object> map = mapper.readValue(response.getEntity().getContent(), Map.class);

			if(response.getStatusLine().getStatusCode() >= 200 && response.getStatusLine().getStatusCode() < 300) {
				System.out.println("Group created " + map);
			}else {
				System.out.println("Error creating group  ");
				if(map != null){
					System.out.println(map.get("error_message"));
				}
			}
		} catch (Exception e) {
			System.out.println(e);
		} finally {
			post.abort();
		}
		
	}
	
	 void updateGroup(String groupToUpdate, String userToGroupUpdate) {

		String url = ConfigServices.getProperty("Url") + ConfigServices.getProperty("GroupEndpoint") + "/" + groupToUpdate + "/members";

		List<Member> userGroup = new ArrayList();
		Member member = new Member();
		member.setMember_id(userToGroupUpdate);
		member.setType("user");
		member.setBase_dn("cn=users,O=IBM,C=US");
		userGroup.add(member);

		Group grp = new Group();
		grp.setMembers(userGroup);

		generateCSRF();

		ObjectMapper mapper = new ObjectMapper();
		String data = "";

		 try {
			 data = mapper.writeValueAsString(grp);
		 } catch (JsonProcessingException e) {
			 e.printStackTrace();
		 }

		HttpPut put = new HttpPut(url);
		try {
						
			if (data != null) {
				put.setEntity(new StringEntity(data));
				put.addHeader("Authorization", ConfigServices.getProperty("AuthorizationBearerToken"));
				put.addHeader("Content-Type", "application/json");
				put.addHeader("IBM-CSRF-TOKEN", csrf_token);
			}
			
			CloseableHttpClient httpClient = HttpClients.createDefault();
			HttpResponse response = httpClient.execute(put);

			Map<String,Object> map = mapper.readValue(response.getEntity().getContent(), Map.class);

			if(response.getStatusLine().getStatusCode() >= 200 && response.getStatusLine().getStatusCode() < 300) {
				System.out.println("Group " + map + "updated successfully");
			}else {
				System.out.println("Error updating the group");

				if(map != null){
					System.out.println(map.get("error_message"));
				}
			}
		} catch (Exception e) {
			System.out.println(e);
		} finally {
			put.abort();
		}
	}
	
	 void deleteGroup(String groupToDelete) {

		String url = ConfigServices.getProperty("Url") + ConfigServices.getProperty("GroupEndpoint") +"/"+ groupToDelete;
		generateCSRF();
		
		HttpDelete delete = new HttpDelete(url);
		try {
		
				delete.addHeader("Authorization", ConfigServices.getProperty("AuthorizationBearerToken"));
				delete.addHeader("Content-Type", "application/json");
				delete.addHeader("IBM-CSRF-TOKEN", csrf_token);
				
			ObjectMapper mapper = new ObjectMapper();
			
			CloseableHttpClient httpClient = HttpClients.createDefault();
			HttpResponse response = httpClient.execute(delete);

			if(response.getStatusLine().getStatusCode() >= 200 && response.getStatusLine().getStatusCode() < 300) {
				System.out.println("Group deleted successfully");
			}else {
				System.out.println("Error deleting the group  /n");
			}
			
		} catch (Exception e) {
			System.out.println(e);
		} finally {
			delete.abort();
		}	
	}
}