//
// return content of xml 
// (used for VOSI capabilityVOSI and availability.xml)
//

import java.io.IOException;
import java.io.PrintWriter;
import java.io.File;
import java.io.OutputStream;
import java.util.Enumeration;
import java.util.*; // ArrayList<String>

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.ServletOutputStream; // for SOOA

// from vlkb_mergefiles.java - dir & file handling
import java.io.*;

import java.nio.file.*;
import static java.nio.file.StandardCopyOption.*;


// serve VOSI resources from xml files (for now implemented as strings, not files FIXME)

public class VlkbServletFile
    extends javax.servlet.http.HttpServlet
{
   String className = this.getClass().getSimpleName();
	private static final Settings settings = Settings.getInstance();
	private boolean available;

	private String checkDatasets(String dirName)
	{
		Path dir = Paths.get(dirName);
      String note;
      try
      {
         int count = 0;
         try (DirectoryStream<Path> stream = Files.newDirectoryStream(dir))
         {
            for (Path entry: stream) count++;
            note = dir.toString() + " has " + String.valueOf(count) + " entries";
				this.available = true;
         }
         catch (DirectoryIteratorException ex)
         {
            // I/O error during the iteration, the cause is an IOException
            throw ex.getCause();
         }
      }
      catch(Exception ex)
      {
         note = "error: " + ex.toString();
			this.available = false;
      }

		return note;
	}

	private String availString()
	{
		String dirName = settings.fitsPaths.surveys();
		String datasetsAvail = checkDatasets(dirName);

		String availStr = 
			"<?xml version=\"1.0\" encoding=\"UTF-8\"?>"
			+ "<vosi:availability xmlns:vosi=\"http://www.ivoa.net/xml/VOSIAvailability/v1.0\">"
			+ "<vosi:available> " +  ((this.available)?"true":"false") + " </vosi:available>"
			+ "<vosi:note> VLKB-SODA " + Version.asString + " is accepting queries </vosi:note>"
			+ "<vosi:note> " + datasetsAvail + " </vosi:note>"
			+ "</vosi:availability>";


		return availStr;
	}



	private String capsStr = null;

	protected void SetCapsStr(String URL, String funcName)
	{
		if(URL != null)
		{

			String accessURL = stripTrailingSlash(URL);

			capsStr =
				"<?xml version=\"1.0\" encoding=\"UTF-8\"?>"

				+ "<vosi:capabilities "
				+    "xmlns:vosi=\"http://www.ivoa.net/xml/VOSICapabilities/v1.0\" "
				+    "xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" "
				+    "xmlns:vod=\"http://www.ivoa.net/xml/VODataService/v1.1\">"

				+ " <capability standardID=\"ivo://ivoa.net/std/VOSI#capabilities\">"
				+ "   <interface xsi:type=\"vod:ParamHTTP\" version=\"1.0\">"
				+ "     <accessURL use=\"full\">"
				+          accessURL + "/capabilities"
				+ "     </accessURL>"
				+ "   </interface>"
				+ " </capability>"

				+ " <capability standardID=\"ivo://ivoa.net/std/VOSI#availability\">"
				+ "   <interface xsi:type=\"vod:ParamHTTP\" version=\"1.0\">"
				+ "     <accessURL use=\"full\">"
				+          accessURL + "/availability"
				+ "     </accessURL>"
				+ "   </interface>"
				+ " </capability>"

				+ " <capability standardID=\"ivo://ivoa.net/std/SODA#sync-1.0\">"
				+ "   <interface xsi:type=\"vod:ParamHTTP\" role=\"std\" version=\"1.0\">"
				+ "     <accessURL use=\"full\">"
				+          accessURL + "/" + funcName
				+ "     </accessURL>"
				+ "   </interface>"
				+ " </capability>"

				+ " <capability standardID=\"ivo://ivoa.net/std/SODA#async-1.0\">"
				+ "   <interface xsi:type=\"vod:ParamHTTP\" role=\"std\" version=\"1.0\">"
				+ "     <accessURL use=\"full\">"
				+          accessURL + "/" + funcName + "_uws/soda_cuts"
				+ "     </accessURL>"
				+ "   </interface>"
				+ " </capability>"

				+ "</vosi:capabilities>";
		}
	}


	String stripTrailingSlash(String path)
	{
		if (path.endsWith("/"))
			return path.substring(0,path.length()-1);
		else
			return path;
	}


	protected void doGet(HttpServletRequest request,
			HttpServletResponse response)
		throws ServletException, IOException {

			doPost(request, response);
		}



	protected void doPost(HttpServletRequest request,
			HttpServletResponse response)
		throws ServletException, IOException
		{
			StringBuffer requestURL = request.getRequestURL();

			System.out.println(className + " vlkb req from: " + request.getRemoteAddr()
					+ " doGet: " + requestURL.toString());

			PrintWriter writer = response.getWriter();
			response.setContentType("text/xml");

			if(-1 != requestURL.lastIndexOf("/capabilities"))
			{
				String fullURL = request.getRequestURL().toString();
				String baseURL = fullURL.substring(0,requestURL.lastIndexOf("/"));

				SetCapsStr(baseURL, "soda");
				writer.println(capsStr);	

			}
			else if(-1 != requestURL.lastIndexOf("/availability"))
			{
				writer.println(availString());	
			}
			// error FIXME what to do if none of above given ? e.g. misconfigured web.xml

			writer.close();
			return;
		}
}

