/*
 *    IIIFXML.java
 *    Copyright (C) 2019 New Zealand Digital Library, http://www.nzdl.org
 *
 *    This program is free software; you can redistribute it and/or modify
 *    it under the terms of the GNU General Public License as published by
 *    the Free Software Foundation; either version 2 of the License, or
 *    (at your option) any later version.
 *
 *    This program is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *    GNU General Public License for more details.
 *
 *    You should have received a copy of the GNU General Public License
 *    along with this program; if not, write to the Free Software
 *    Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
 */
package org.greenstone.gsdl3.util;

import org.greenstone.util.GlobalProperties;

import org.w3c.dom.*;

import java.io.*;
import java.net.*;
import java.util.*;
import java.text.DateFormat;
import java.text.SimpleDateFormat;

// import file Logger.java
import org.apache.log4j.*;

/** these constants are used for the IIIF service */
public class IIIFXML {
  
  static Logger logger = Logger.getLogger(org.greenstone.gsdl3.util.IIIFXML.class.getName());

  // the leading keyword of IIIF protocol // ****
  public static final String VERB = "verb";

  // Possible states for non-IIIF/non-verb activate/deactivate requests  
  public static final int DEACTIVATION = 0;
  public static final int ACTIVATION = 1;
  
  // one valid iiif verb // ****
  public static final String GET_RECORD = "GetRecord";
    
  // iiif request parameters
  public static final String IDENTIFIER = "identifier";
    
  // Error element and code att
  public static final String ERROR = "error";
  public static final String CODE = "code";
  
  // IIIF error codes
  public static final String ID_DOES_NOT_EXIST = "idDoesNotExist";
  public static final String BAD_ARGUMENT      = "badArgument";
  public static final String BAD_VERB          = "badVerb";
    
  // General
  public static final String IIIF_PMH = "IIIF-PMH"; // ****
    //public static final String RESPONSE_DATE = "responseDate"; // ****
  public static final String REQUEST = "request";
    
  // Identify data
  // OAI replacing => IIIF, maybe want baseURL and oai-identifier
  public static final String BASE_URL = "baseURL";
    
  // record response data
  public static final String RECORD = "record";
  public static final String HEADER = "header";
  public static final String METADATA = "metadata";

  public static final String OID = "OID"; // ****
    
  public static final String IIIF_SERVICE_RACK = "IIIFPMH";

  /*************************above are final values****************************/

  public static Element iiif_config_elem = null;
    
  public static final String iiif_version = "2.1"; // ****
  public static String baseURL = "";
    
  /** Converter for parsing files and creating Elements */
  public static XMLConverter converter = new XMLConverter();
  
  public static String[] special_char = {"/", "?", "#", "=", "&", ":", ";", " ", "%", "+"};
  public static String[] escape_sequence = {"%2F", "%3F", "%23", "%3D", "%26", "%3A", "%3B", "%20", "%25", "%2B"};

  public static String getIIIFVersion() {
    return iiif_version;
  }
	
  public static String getBaseURL() {
    return baseURL;
  }
	
  /** Read in IIIFConfig.xml (residing web/WEB-INF/classes/) and use it to configure the receptionist etc.
   *  the baseURL variables are also set in here. 
   *  The init() method is also called in here. */ 
  public static Element getIIIFConfigXML() {
     
    File iiif_config_file = null;

    try {
      URL iiif_config_url = Class.forName("org.greenstone.gsdl3.IIIFServerBridge").getClassLoader().getResource("IIIFConfig.xml");
      if (iiif_config_url == null) {
	logger.error("couldn't find IIIFConfig.xml via class loader");
	return null;
      }
      iiif_config_file = new File(iiif_config_url.toURI());
      if (!iiif_config_file.exists()) {
        logger.error(" IIIF config file: "+iiif_config_file.getPath()+" not found!");
        return null;
      }
    } catch(Exception e) {
      logger.error("couldn't find IIIFConfig.xml "+e.getMessage());
      return null;
    }

    Document iiif_config_doc = converter.getDOM(iiif_config_file, "utf-8");
    if (iiif_config_doc != null) {
      iiif_config_elem = iiif_config_doc.getDocumentElement();
    } else {
      logger.error("Failed to parse IIIF config file IIIFConfig.xml.");
      return null;
    }
          
    // initialize baseURL
    Element base_url_elem = (Element)GSXML.getChildByTagName(iiif_config_elem, BASE_URL);
    baseURL = GSXML.getNodeText(base_url_elem);

    return iiif_config_elem;
  }

    
  /** TODO: returns a basic response (loosely based on OAI XML message)
   *  
   */
    public static  Element createBasicResponse(Document doc, String verb, String[] pairs) { // ****

    Element response = createResponseHeader(doc, verb);
      
    //set the responseDate and request elements accordingly
    Element request_elem = (Element)GSXML.getChildByTagName(response, REQUEST);
    if (verb.equals("")) {
      request_elem.setAttribute(VERB, verb);
    }
    int num_pairs = (pairs==null)? 0 : pairs.length;
    for (int i=num_pairs - 1; i>=0; i--) {
      int index = pairs[i].indexOf("=");
      if (index != -1) {
	String[] strs = pairs[i].split("=");
	if(strs != null && strs.length == 2) {
	  request_elem.setAttribute(strs[0], iiifDecode(strs[1]));
	}
      }
    }//end of for()
      
    GSXML.setNodeText(request_elem, baseURL);
      
    return response;
  }
    
  /** @param error_code the value of the code attribute
   *  @param error_text the node text of the error element
   *  @return an iiif error <message><response><error>
   */
  public static Element createErrorMessage(String error_code, String error_text) {
    Document doc = converter.newDOM();
    Element message = doc.createElement(GSXML.MESSAGE_ELEM);
    Element resp = doc.createElement(GSXML.RESPONSE_ELEM);
    message.appendChild(resp);
    Element error = createErrorElement(doc, error_code, error_text);
    resp.appendChild(error);
    return message;
  }
    
  /** @param error_code the value of the code attribute
   *  @param error_text the node text of the error element
   *  @return an iiif error <response><error>
   */
  public static Element createErrorResponse(String error_code, String error_text) {
    Document doc = converter.newDOM();
    Element resp = doc.createElement(GSXML.RESPONSE_ELEM);
    Element error = createErrorElement(doc, error_code, error_text);
    resp.appendChild(error);
    return resp;
  }
    
  /** @param error_code the value of the code attribute
   *  @param error_text the node text of the error element
   *  @return an iiif error <error>
   */
  public static Element createErrorElement(Document doc, String error_code, String error_text) {
    Element error = doc.createElement(ERROR);
    error.setAttribute(CODE, error_code);
    GSXML.setNodeText(error, error_text);
    return error;
  }

  // This is the response message sent when there's a request to activate/deactivate a non-IIIF collection
  // A request to activate a non-existent/non-IIIF collection is not invalid, it's just that we won't process it.
  // So we still return status code OK (OK status code is needed for servercontrol.pm of activate.pl to recognise
  // that the command had been "successful" when it runs de/activate).
  public static Element createDeActivationOfNonIIIFCollResponse(int activationState, String collname) {
	Document doc = converter.newDOM();
    Element response = doc.createElement(GSXML.RESPONSE_ELEM);
	response.setAttribute("status", "OK"); 
	String message = "collection: " + collname + " is not enabled for IIIF.";
	if(activationState == ACTIVATION) {
		message += " Not attempting to activate it.";
	  } else {
		message += " Not attempting to deactivate it.";
	  }
	  GSXML.setNodeText(response, message);
	  return response;
  }
  
  // The response message sent when a request comes in to activate/deactivate a proper IIIF collection.
   public static Element createActivationStateResponse(boolean success, int activationState, String collname) {
    Document doc = converter.newDOM();
    Element response = doc.createElement(GSXML.RESPONSE_ELEM);
    if (success) {
      response.setAttribute("status", "OK");
	  if(activationState == ACTIVATION) {
		GSXML.setNodeText(response, "collection: " + collname + " activated");
	  } else {
		GSXML.setNodeText(response, "collection: " + collname + " deactivated");  
	  }
    } else {
      response.setAttribute("status", "FAIL");
	  if(activationState == ACTIVATION) {
		GSXML.setNodeText(response, "Failed to activate collection " + collname);
	  } else {
		GSXML.setNodeText(response, "Failed to deactivate collection " + collname);
	  }
    }
    return response;
  }
  
  public static Element createResetResponse(boolean success) {
    Document doc = converter.newDOM();
    Element response = doc.createElement(GSXML.RESPONSE_ELEM);
    if (success) {
      response.setAttribute("status", "OK");
      GSXML.setNodeText(response, "Reset IIIFServerBridge successfully");
    } else {
      response.setAttribute("status", "FAIL");
      GSXML.setNodeText(response, "Failed to reset IIIFServerBridge");
    }
    return response;
  }
  /** convert the escaped sequences (eg, '%3A') of those special characters back to their
   *  original form (eg, ':'). 
   */
  public static String iiifDecode(String escaped_str) {
    logger.info("iiifDecode() " +escaped_str);
    for (int i=0; i<special_char.length; i++) {
      if (escaped_str.indexOf(escape_sequence[i]) != -1) {
	escaped_str = escaped_str.replaceAll(escape_sequence[i], special_char[i]);
      }
    }
    return escaped_str;        
  }
  /** convert those special characters (eg, ':') to their
   *  escaped sequences (eg, '%3A'). 
   */
    /*
    public static String iiifEncode(String original_str) { // ****
    logger.info("iiifEncode() " + original_str);      
    for (int i=0; i<special_char.length; i++) {
      if (original_str.indexOf(special_char[i]) != -1) {
	original_str = original_str.replaceAll(special_char[i], escape_sequence[i]);
      }
    }
    return original_str;  
  }
    */
    
  public static Element createResponseHeader(Document response_doc, String verb) {
    String tag_name = IIIF_PMH;
    Element iiif = response_doc.createElement(tag_name);
    Element req = response_doc.createElement(REQUEST);
    iiif.appendChild(req);

    return iiif;
  }    
}






