package com.iit;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.PrintWriter;

import org.json.JSONObject;

import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class JSONReaderServlet
 */
public class JSONReaderServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public JSONReaderServlet() {
		super();
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {


	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		String dataPart = null;

		try {
			StringBuilder sb = new StringBuilder();
			BufferedReader br = request.getReader();
			String str = null;
			while ((str = br.readLine()) != null) {
				sb.append(str);
			}

			dataPart = sb.toString();
		} catch (Exception e) {
			e.printStackTrace();

			PrintWriter printWriter = response.getWriter();
			printWriter.println("UNPARSABLE_REQUEST_DATA_PART");
			printWriter.close();
			return;
		}

		if (dataPart == null) {
			PrintWriter printWriter = response.getWriter();
			printWriter.println("MISSING_DATA");
			printWriter.close();
			return;
		}

		if ("".equalsIgnoreCase(dataPart)) {
			PrintWriter printWriter = response.getWriter();
			printWriter.println("No data was sent in body!");
			printWriter.close();
			return;
		}

		try {
			// Parse response as json
			JSONObject jsonObj = new JSONObject(dataPart);
			System.out.println(dataPart);
			
			String first_name = null;
			String last_name = null;
			
			if (jsonObj.has("first_name"))
				first_name = jsonObj.getString("first_name");

			if (jsonObj.has("last_name"))
				last_name = jsonObj.getString("last_name");
			
			if (first_name != null && last_name != null) {
				PrintWriter printWriter = response.getWriter();
				printWriter.println("Name: " + first_name + " " + last_name);
				printWriter.close();
			}else {
				PrintWriter printWriter = response.getWriter();
				printWriter.println("Empty data was sent!");
				printWriter.close();
			}
			
			// System.out.println("Sending to client: " + result);


		} catch (Exception e) {
			e.printStackTrace();
			PrintWriter printWriter = response.getWriter();
			printWriter.println("UNPARSABLE_JSON");
			printWriter.close();
		}
	}
}
