package com.bankaudit.util;

import java.nio.charset.Charset;

import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.JSONValue;
import org.json.simple.parser.JSONParser;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.web.client.HttpStatusCodeException;
import org.springframework.web.client.RestTemplate;

import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;



public class TestClass {

	static RestTemplate restTemplate = new RestTemplate();
	public static void main(String[] args) {
		
		System.out.println("Inside TestClass ..=>");
		// testRestTemplate();
		// testStrin2JSONConvert();
		// convertString();
		testRestTemplateResponseError();
		
	}
	
	public static void testRestTemplate() {
		
		HttpHeaders headers = new HttpHeaders();
		
		//You can use more methods of HttpHeaders to set additional information
		// set `content-type` and other headers
		headers.setContentType(MediaType.APPLICATION_JSON);
		headers.set("APIKey","a123w");
		headers.set("version","2");
		
		System.out.println("headers ..=>"+ headers);
		
		// TODO Auto-generated method stub
		String unitCodeP1="TS";  // License Code
		//String financialYearP3=myAuditsService.getFinancialYearByAuditId(legalEntityCode, auditTypeCode, auditId);
		String financialYearP3="2024-12-31";
		String auditTypeCodeP2="RRB";

		
		// request body parameters
		JSONObject ensureRequest = new JSONObject();
		ensureRequest.put("licensee_Code", unitCodeP1);
		ensureRequest.put("licensee_Subtype", "");
		ensureRequest.put("financial_Year", financialYearP3);
		ensureRequest.put("inspection_Frequency", 1);
		
		System.out.println("ensureRequest ..=> "+ ensureRequest);
		
		//HttpEntity<JSONObject> requestEnty = new HttpEntity<>(ensureRequest, headers);
		HttpEntity<String> requestEnty = new HttpEntity<String>(ensureRequest.toString(), headers);
		
		System.out.println("requestEnty ..=> "+ requestEnty);
		try {
			// convert your request body to JSON formatted string using writeValueAsString() method of ObjectMapper
			ObjectMapper om = new ObjectMapper();
			om.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
			String reqBodyData = om.writeValueAsString(ensureRequest); 
			System.out.println("reqBodyData ..=> "+ reqBodyData);
		}catch(Exception e){
			e.printStackTrace(System.out);
		}
	}

	public static void testStrin2JSONConvert() {
		System.out.println(" Inside testStrin2JSONConvert .. " );
		String str="{Wtate=0, msg=CSV Generated Successfully, data=Resources\\CSVExtraction\\TS_Inspection Report CSV_RRB_1_24022025183023.csv, results={status=200, msg=CSV Generated Successfully, userType=}, userType=}";
		System.out.println("Str ... "+ str);
		
		String str1=str.replace("=", ":");
		System.out.println("Str1 ... "+ str1);
		
		Object str2="{state=0, msg=CSV Generated Successfully, data=Resources\\CSVExtraction\\TS_Inspection Report CSV_RRB_1_24022025183023.csv, results={status=200, msg=CSV Generated Successfully, userType=}, userType=}";
		
		String jsonString = "{\"name\":\"sonoo\",\"details\":{\"age\":27,\"salary\":600000.0}}";  
        JSONObject jsonObject = (JSONObject) JSONValue.parse(jsonString);  
        String name = (String) jsonObject.get("name");  
        System.out.println("name .. "+name);
        
        
        
        JSONObject jsonObject1 = (JSONObject) JSONValue.parse(jsonString);  
        String state = (String) jsonObject.get("state");  
        System.out.println("state .. "+state);
		
         try {
        	 ObjectMapper mapper = new ObjectMapper();  
        	 String json0 = mapper.writeValueAsString(str2);
        	 System.out.println("json0  .... => "+ json0);
        	 
        	 String json = new ObjectMapper().writeValueAsString(str);
        	 System.out.println("json  .... => "+ json);
        	 
     	//	JSONObject respJson = new JSONObject(str);
     	//	System.out.println("respJson  .... => "+ respJson);
     		
        //logger.info(response.getBody());
        JSONParser parser=new JSONParser();
        org.json.simple.JSONObject jsonObject2=(org.json.simple.JSONObject) parser.parse(str.toString());
        
        System.out.println("jsonObject1  .... => "+ jsonObject1);
         }catch(Exception e) {
        	 e.printStackTrace(System.out);
         }
		
	}
	
	public static void convertString() {
		
		String jsonString = "{\"name\":\"sonoo\",\"details\":{\"age\":27,\"salary\":600000.0}}";  
		System.out.println("jsonString .. "+jsonString);
		JSONObject jsonObject0 = (JSONObject) JSONValue.parse(jsonString);  
        String name0 = (String) jsonObject0.get("name");  
        System.out.println("name .. "+name0);
		
        String resStr="{state=0, msg=CSV Generated Successfully, data=Resources\\CSVExtraction\\TS_Inspection Report CSV_RRB_1_24022025183023.csv, results={status=200, msg=CSV Generated Successfully, userType=}, userType=}";
        
		// String jsonString = "{\"name\":\"sonoo\",\"details\":{\"age\":27,\"salary\":600000.0}}";
		//String jsonString1 = "{state=0, msg=5}";
        String jsonString1 = "{state=0, msg=CSV Generated Successfully, data=Resources\\\\CSVExtraction\\\\TS_Inspection Report CSV_RRB_1_24022025183023.csv, results={status=200, msg=CSV Generated Successfully, userType=}, userType=}";
	    jsonString1=jsonString1.replace("{", "{\"");
	    jsonString1=jsonString1.replace("=", "\":\"");
	    jsonString1=jsonString1.replace(", ", "\",\"");
	    jsonString1=jsonString1.replace("}", "\"}");
	    
	    jsonString1=jsonString1.replace(":\"{\"", ": {\"");
	    jsonString1=jsonString1.replace("\"}\",", "\"},");
	    
	    System.out.println("jsonString1 .. "+jsonString1);
	    
	    JSONObject jsonObject = (JSONObject) JSONValue.parse(jsonString1);  
	    System.out.println("jsonObject .. "+jsonObject);
        String name = (String) jsonObject.get("state");  
        System.out.println("state .. "+name);
        System.out.println("msg .. "+(String) jsonObject.get("msg"));
        JSONObject jarr=(JSONObject)jsonObject.get("results");
        
        System.out.println("status .. "+(String) jarr.get("status"));
	}

	public static void testRestTemplateResponseError() {
		
		HttpHeaders headers = new HttpHeaders();
		
		//You can use more methods of HttpHeaders to set additional information
		// set `content-type` and other headers
		headers.setContentType(MediaType.APPLICATION_JSON);
		headers.set("APIKey","a123w");
		headers.set("version","2");
		
		System.out.println("headers ..=>"+ headers);
		
		// TODO Auto-generated method stub
		String unitCodeP1="TS";  // License Code
		//String financialYearP3=myAuditsService.getFinancialYearByAuditId(legalEntityCode, auditTypeCode, auditId);
		String financialYearP3="2024-12-31";
		String auditTypeCodeP2="RRB";

		
		// request body parameters
		JSONObject ensureRequest = new JSONObject();
		ensureRequest.put("licensee_Code", unitCodeP1);
		ensureRequest.put("licensee_Subtype", "");
		ensureRequest.put("financial_Year", financialYearP3);
		ensureRequest.put("inspection_Frequency", 1);
		
		System.out.println("ensureRequest ..=> "+ ensureRequest);
		
		//HttpEntity<JSONObject> requestEnty = new HttpEntity<>(ensureRequest, headers);
		HttpEntity<String> requestEnty = new HttpEntity<String>(ensureRequest.toString(), headers);
		
		restTemplate.getMessageConverters().add(0, new StringHttpMessageConverter(Charset.forName("UTF-8")));
		
		ResponseEntity<Object> response =null;
		try {
			// send POST request
	        //ResponseEntity<String> response = restTemplate.postForEntity(baseUri+extApi, requestEnty, String.class);
			response = restTemplate.exchange("http://74.208.121.199:8080/baasDOSLcl/#/login",HttpMethod.POST, requestEnty, Object.class);
		}catch(HttpStatusCodeException e) {
			System.out.println("Inside Exception"+e.getRawStatusCode());
		        ResponseEntity.status(e.getRawStatusCode()).headers(e.getResponseHeaders())
		                .body(e.getResponseBodyAsString());
		} 
		System.out.println("The values are");
		System.out.println("response ..=>"+ response);
		System.out.println("response getBody()..=>"+ response.getBody());
		System.out.println("response getStatusCode()..=>"+ response.getStatusCode());
	}
	
}
