package ibase.webitm.utility;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.Base64;
import java.util.List;

import ibase.system.config.ConnDriver;
import ibase.utility.BaseLogger;
import ibase.utility.UserInfoBean;
import org.json.JSONObject;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;


public class DocumentViewerServiceUtility extends RestAPIServiceUtility {

	/*
	 * Params: objName refID This will contain logic to first get doc ID's against
	 * the objName and refID via getDocumentData's method
	 * 
	 */
	public JSONObject getPreviewImage(String objName, String refId, String tokenIDfromHeader) {
	    BaseLogger.log("3", null, null, " getPreviewImage method call: ");
	    JSONObject jsonObject = new JSONObject();

	    UserInfoBean userInfo = null;

	    if (userInfo == null) {
	        APIUtility apiUtility = new APIUtility();
	        userInfo = apiUtility.createUserInfoFromJWTToken(tokenIDfromHeader);
	        BaseLogger.log("3", null, null, "USER_INFO created from TOKEN: [" + userInfo + "]");
	    }

	    DocumentHandlerServiceUtility documentHandlerServiceUtility = new DocumentHandlerServiceUtility();
	    String responseData = null;
	    String refCol = "";
	    byte[] byteArray = null;
	    try {

	        responseData = documentHandlerServiceUtility.getDocumentData(objName, refId, tokenIDfromHeader,refCol);
	        BaseLogger.log("3", null, null, "responseData ==> " + responseData);

	        List<String> documentIds = new ArrayList<>();

	        try {
	            // Parse JSON string to JsonNode
	            ObjectMapper objectMapper = new ObjectMapper();
	            JsonNode rootNode = objectMapper.readTree(responseData);

	            // Extract Document_Id values
	            documentIds = new ArrayList<>();
	            JsonNode documentsNode = rootNode.path("Documents");
	            if (documentsNode.isArray()) {
	                for (JsonNode documentNode : documentsNode) {
	                    JsonNode documentIdNode = documentNode.path("Document_Id");
	                    if (documentIdNode.isTextual()) {
	                        documentIds.add(documentIdNode.asText());
	                    }
	                }
	            }

	            // Print the list of Document_Id values
	            System.out.println("Document IDs: " + documentIds);
	        } catch (IOException e) {
	            e.printStackTrace();
	        }
	        
	        if (documentIds.isEmpty()) 
	        {
                BaseLogger.log("3", null, null, "Inside the if ,docId not found  :");

	            jsonObject.put("error", " No Documemt found against Object: " + objName + "and Ref ID: " + refId);
	            return jsonObject;
	        }

	        for (String docId : documentIds) {

	            try {
	                BaseLogger.log("3", null, null, "DocumentViewerServlet :: docID [" + docId + "]");
	                byteArray = getPreviewImageAgainstDocId(docId, userInfo);

	                String encodedByteArray = Base64.getEncoder().encodeToString(byteArray);
	                jsonObject.put(docId, encodedByteArray);
	            } catch (Exception ex) {
	                BaseLogger.log("3", null, null, "Exception in DocumentViewerServlet :: handleDocument() : " + ex);
	                ex.printStackTrace();
	            }
	        }
	    } catch (Exception e) {
	        BaseLogger.log("3", null, null, "Exception :: " + e);

	        e.printStackTrace();
	    }
	    BaseLogger.log("3", null, null, "jsonObject with docID and encoded byte array0:: [" + jsonObject + "]");
	    BaseLogger.log("3", null, null, "byteArray  of:: [" + byteArray.toString() + "]");

	    return jsonObject;
	}


	private byte[] getPreviewImageAgainstDocId(String docId, UserInfoBean userInfo) {
		BaseLogger.log("3", null, null, "getPreviewImageAgainstDocId Service Called");

		byte[] byteArray = null;

		try {
			BaseLogger.log("3", null, null,
					"DocumentViewerServlet :: handleDocument() : GET_VIDEO_FRAME : docID [" + docId + "]");

			if (docId == null || "".equals(docId.trim()))
				byteArray = new byte[] { 0 };
			else {
				byteArray = getVideoFrame(docId, userInfo);
				byteArray = (byteArray == null) ? new byte[] { 0 } : byteArray;
			}
		} catch (Exception ex) {
			BaseLogger.log("3", null, null, "Exception in DocumentViewerServlet :: handleDocument() : " + ex);
			ex.printStackTrace();
		}
		BaseLogger.log("3", null, null, " getPreviewImageAgainstDocId byteArray:: " + byteArray);

		return byteArray;
	}

	// getPreviewImageAgainstDocId(List docId's)
	private byte[] getVideoFrame(String docId, UserInfoBean userInfo) {
		BaseLogger.log("3", null, null, "getVideoFrame() Called");

		Connection conn = null;
		Statement st = null;
		ResultSet rs = null;
		InputStream inputStream = null;
		byte[] iconByteArray = { 0 };
		BaseLogger.log("3", null, null, " getVideoFrame method call: ");

		try {
			String sql = "SELECT ICON FROM DOC_CONTENTS WHERE DOC_ID = " + docId;
			BaseLogger.log("3", userInfo, null, "DocumentViewerServlet :: getVideoFrame() : sql [" + sql + "]");
			String transDB = userInfo.getTransDB();
			conn = new ConnDriver().getConnectDB(transDB);
			st = conn.createStatement();

			rs = st.executeQuery(sql);

			if (rs.next()) {
				inputStream = rs.getBinaryStream(1);

				if (inputStream != null) {
					ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
					int i = 0;

					while ((i = inputStream.read()) != -1)
						byteArrayOutputStream.write(i);

					iconByteArray = byteArrayOutputStream.toByteArray();
				}
			}
		} catch (Exception ex) {
			BaseLogger.log("3", userInfo, null, "Exception in DocumentViewerServlet :: getVideoFrame() : " + ex);
		} finally {
			try {
				if (conn != null)
					conn.close();
				if (st != null)
					st.close();
				if (rs != null)
					rs.close();
			} catch (Exception ex) {
			}
		}
		BaseLogger.log("3", userInfo, null, "getVideoFrame iconByteArray : " + iconByteArray);

		return iconByteArray;
	}
}
