/*
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.Details;
import model.Groups;
import model.User;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
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 org.json.JSONObject;
import services.ConfigServices;

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

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

		HttpPost post = null;
		try {
			String url = ConfigServices.getProperty("Url") + ConfigServices.getProperty("CSRFTokenEndpoint");

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

			  post = new HttpPost(url);

				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 createUser(String user_id) {
		
		User user = new User();
		user.setUserId(user_id);
		user.setBaseDn("cn=users,O=IBM,C=US");
		user.setEmail(user_id);
		List<Groups> usergroup = new ArrayList();
		Groups grp = new Groups();
		grp.setName("Developers");
		grp.setBase_dn("cn=groups,O=IBM,C=US");
		usergroup.add(grp);
		user.setGroups(usergroup);
		
		ObjectMapper mapper = new ObjectMapper();
		
		String data = "";
		try {
			data = mapper.writeValueAsString(user);
		} catch (JsonProcessingException e) {
			e.printStackTrace();
		}
		
		generateCSRF();
		String url = ConfigServices.getProperty("Url") + ConfigServices.getProperty("UserEndpoint");

		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("User " + map + "created successfully");
			}else {
				System.out.println("Error creating the user /n");

				if(map != null){
					System.out.println(map.get("error_message"));
				}
			}
					
		} catch (Exception e) {
			System.out.println(e);
		} finally {
			post.abort();
		}		
	}
	
	 void createUsers(List users) {
		
		ObjectMapper mapper = new ObjectMapper();
		
		String data = "";

		Map<String,List<User> > mapUser = new HashMap<>();

		 mapUser.put("users", users);
		
		String usersString = "";
		try {
			usersString = mapper.writeValueAsString(mapUser);
		} catch (JsonProcessingException e1) {
			e1.printStackTrace();
		}
			
		generateCSRF();
		
		data = usersString;
		String url = ConfigServices.getProperty("Url") + ConfigServices.getProperty("CreateBulkUsersEndpoint");

		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("User " + map + "created");
			}else {
				System.out.println("Error creating the user /n");

				if(map != null){
					System.out.println(map.get("error_message"));
				}

			}
		} catch (Exception e) {
			System.out.println(e);
		} finally {
			post.abort();
		}
		
	}
	
	 void updateUser(String user_id, String given_name, String family_name, String preferred_language, String group_name) {

		String url = ConfigServices.getProperty("Url") + ConfigServices.getProperty("UserEndpoint") + "/" +user_id + "?update_mode=merge";
		
		generateCSRF();
		
		JSONObject jsonObj = new JSONObject();
		Details details = new Details();
		details.setPreferredLanguage(preferred_language);

		List<Groups> userGroupList = new ArrayList<>();
		Groups userGroup = new Groups();
		userGroup.setName(group_name);
		userGroup.setBase_dn("cn=groups,O=IBM,C=US");
		userGroupList.add(userGroup);

		 User user = new User();
		 user.setGivenName(given_name);
		 user.setFamilyName(family_name);
		 user.setDetails(details);
		 user.setGroups(userGroupList);

		ObjectMapper mapper = new ObjectMapper();

		 String data = "";
		 try {
			 data = mapper.writeValueAsString(user);
		 } catch (JsonProcessingException e) {
			 e.printStackTrace();
		 }

		HttpPut put = new HttpPut(url);
		try {
			
			generateCSRF();
			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("User " + map + "updated successfully");
			}else {
				System.out.println("Error updating the user /n");

				if(map != null){
					System.out.println(map.get("error_message"));
				}

			}
			
		} catch (Exception e) {
			System.out.println(e);
		} finally {
			put.abort();
		}
		
	}
	
	 void deleteUser(String uid) {

		 String url = ConfigServices.getProperty("Url") + ConfigServices.getProperty("UserEndpoint") +"/"+ uid;
	
		HttpDelete delete = new HttpDelete(url);
		try {
			generateCSRF();
			
			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("User deleted successfully");
			}else {
				System.out.println("Error deleting the user : /n");

				Map<String, Object> map = mapper.readValue(response.getEntity().getContent(), Map.class);
				if (map != null) {
					System.out.println(map.get("error_message"));
				}
			}
		} catch (Exception e) {
			System.out.println(e);
		} finally {
			delete.abort();
		}
	}
}