package com.k_int.ia.sru;

import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.util.*;
import org.apache.commons.fileupload.*;
import com.k_int.ia.metadata_submission.*;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

public class SRU extends HttpServlet {

  public SRU() {
  }

  public void init(ServletConfig config) throws ServletException {
    super.init(config);
  }


  public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    doPost(request, response);
  }

  public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    try {
      System.err.println("SRU::doPost");
      response.getWriter().println("<response></response>");
      String operation = request.getParameter("operation");
      System.err.println("operation="+operation);

      if ( operation != null ) {
        if ( operation.toLowerCase().startsWith("info:srw/operation/1/" ) ) {
          if ( operation.toLowerCase().equals("info:srw/operation/1/update" ) ) {
            System.err.println("Record Update");
            processRecordUpdate(request,response);
          }
        }
      }
    }
    finally {
      System.err.println("SRU::doPost complete");
    }
  }

  private void processRecordUpdate(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    String identifier = request.getParameter("identifier");
    String record_source = request.getParameter("record_source");
    String publisher_identity = request.getParameter("publisher_identity");
    String publisher_credentials = request.getParameter("publisher_credentials");
    String target_collection = request.getParameter("target_collection");

    try {
      boolean isMultipart = FileUpload.isMultipartContent(request);
      if ( isMultipart ) {
        DiskFileUpload upload = new DiskFileUpload();
        List /* FileItem */ items = upload.parseRequest(request);

        Iterator iter = items.iterator();
        while (iter.hasNext()) {
          FileItem item = (FileItem) iter.next();
          System.err.println("field name:"+item.getFieldName());
          System.err.println("file name:"+item.getName());
          System.err.println("In mem:"+item.isInMemory());
          if (item.isFormField()) {
            String record = item.getString();
            publish(identifier,record_source,publisher_identity,publisher_credentials,target_collection,record);
          } else {
            // processUploadedFile(item);
            String record = item.getString();
            publish(identifier,record_source,publisher_identity,publisher_credentials,target_collection,record);
          }
        }
      }
      else {
        System.err.println("Not multipart");
      }
    } catch ( org.apache.commons.fileupload.FileUploadException fue ) {
      fue.printStackTrace();
    }
  }

  private void publish(String identifier,
                       String record_source,
                       String publisher_identity,
                       String publisher_credentials,
                       String target_collection,
                       String record) {

    WebApplicationContext ctx =
      WebApplicationContextUtils.getRequiredWebApplicationContext(
        getServletContext());

    try {
      com.k_int.ia.metadata_submission.MetadataSubmissionService ss = (com.k_int.ia.metadata_submission.MetadataSubmissionService) ctx.getBean("SubmissionService");

      SubmissionResult sr = ss.submit(identifier,
                                      null,
                                      null,
                                      record_source,
                                      publisher_identity,
                                      publisher_credentials,
                                      target_collection,
                                      record,
                                      null);
    }
    catch ( SubmissionException se ) {
      se.printStackTrace();
    }

  }
}
