package com.azuredemo.core.servlets;

import com.azuredemo.core.SaveAndFetchFromAzure.StoreAndFetchDataFromAzureStorage;
import org.apache.sling.api.SlingHttpServletRequest;
import org.apache.sling.api.SlingHttpServletResponse;
import org.apache.sling.api.servlets.SlingAllMethodsServlet;
import org.apache.sling.servlets.annotations.SlingServletResourceTypes;
import org.osgi.service.component.annotations.Component;
import org.osgi.service.component.annotations.Reference;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.jcr.RepositoryException;
import javax.jcr.Session;
import javax.servlet.Servlet;
import java.io.IOException;
import java.io.Serializable;

@Component(
        service={Servlet.class }
)

@SlingServletResourceTypes(
        resourceTypes="azure/getBlobsByIndexTags",
        methods= "GET",
        extensions="json"
)

public class GetBlobsByMetdaDataTags extends SlingAllMethodsServlet implements Serializable {
    private static final long serialVersionUID = 1L;
    private final transient Logger log = LoggerFactory.getLogger(this.getClass());


    @Reference transient 
    StoreAndFetchDataFromAzureStorage   azurePortalBlobs;

    protected void doGet(SlingHttpServletRequest request, SlingHttpServletResponse response) {
        log.debug("Got into my servlet to get search results"+request.getParameter("searchCriteria"));
        String formPath = request.getParameter("formPath");
        log.debug("The form Path is"+formPath);

        String submittedFormName="";
        String metaDataQuery="";
        Session session = request.getResourceResolver().adaptTo(Session.class);
        try {
            submittedFormName = session.getNode(request.getParameter(("formPath"))).getParent().getName();
            log.debug("The form name is   "+submittedFormName);

            metaDataQuery = "formName="+"'"+submittedFormName+"' AND "+request.getParameter("searchCriteria");
            log.debug("##### The query is ######   "+metaDataQuery);

        } catch (RepositoryException e) {
            throw new RuntimeException(e);
        }

        try {
            String blobs = azurePortalBlobs.getBlobs(metaDataQuery);
            response.setContentType("application/json");
            response.setCharacterEncoding("UTF-8");
            System.out.println("The json response is "+blobs);
            response.getWriter().write(blobs);

            // response.getWriter().write(ja.toString());


        } catch (IOException e) {
            throw new RuntimeException(e);
        }


    }
}
