package jp.hasc.loggerserver;
import java.io.ByteArrayInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.StringWriter;
import java.io.UnsupportedEncodingException;
import java.util.Enumeration;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.ParameterParser;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IFolder;

/**
 * 旧バージョンのServletです。
 * 過去のHascLoggerからのupload時に利用します。
 * @author iwasaki
 */
@SuppressWarnings({"rawtypes","unused"})
public class HascUploaderServletOld extends HttpServlet
{
	/**
	 * 
	 */
	private static final long serialVersionUID = -4718231431886490254L;

	//	static String basePath ="C:/accdata";
	//public static IFolder basefolder = null;

	public HascUploaderServletOld(){}
	public HascUploaderServletOld(String greeting)
	{
	}
	byte []boundary;

	protected byte[] getBoundary(String contentType) {
		ParameterParser parser = new ParameterParser();
		parser.setLowerCaseNames(true);
		// Parameter parser can handle null input
		Map params = parser.parse(contentType, new char[] {';', ','});
		String boundaryStr = (String) params.get("boundary");

		if (boundaryStr == null) {
			return null;
		}
		byte[] boundary;
		try {
			boundary = boundaryStr.getBytes("ISO-8859-1");
		} catch (UnsupportedEncodingException e) {
			boundary = boundaryStr.getBytes();
		}
		return boundary;
	}



	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
	{
		response.setContentType("text/html");
		response.setStatus(HttpServletResponse.SC_OK);
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse response)
	throws ServletException, IOException {
		//		System.out.println("DoPost");
		Enumeration en = req.getAttributeNames();
		String st;
		/*		while (en.hasMoreElements()){
			 st = (String)en.nextElement();
			System.out.println("Got "+st);			 
		}
		en = req.getHeaderNames();
		while (en.hasMoreElements()){
			 st = (String)en.nextElement();
			System.out.println(st+":"+req.getHeader(st));			 
		}
//		System.out.println("Length:"+len);

		en = req.getParameterNames();
		while (en.hasMoreElements()){
			 st = (String)en.nextElement();
//			System.out.println("Param["+st+"]="+req.getParameter(st));
		}

//		System.out.println("PathInfo:"+req.getPathInfo());
//		System.out.println("ContextPath:"+req.getContextPath());
//		System.out.println("QueryString:"+req.getQueryString());
		 */
		int len = req.getContentLength();
		boundary = getBoundary(req.getHeader("Content-Type"));
		//		System.out.println("boundary:"+new String(boundary));
		ServletInputStream sis = req.getInputStream();
		if( len > 1024 * 1024 * 50 ){ // over 2048 Kbyte too big.(2min = about 700kbyte)
			response.setContentType("text/plain");
			response.setStatus(HttpServletResponse.SC_BAD_REQUEST);	 // toobig!		
			return;
		}
		byte[] buf = new byte[len];
		//		sis.read(buf,len);		
		int k;
		int off = 0;
		int rest = len;
		//		System.out.println("AvailSize:"+sis.available()); (Always zero...)

		//		while(sis.available()>0){
		while(off < len){
			k = sis.read(buf,off,rest);
			if(k < 0) break;
			//			System.out.println("Read:"+off+"-"+k+" rest "+(rest-k));
			if( off+k <= len ){
				rest -=k;
				off +=k;
			}
		}

		String s = new String(buf);

		String bd = new String(boundary);
		int bdp=0;
		String ss = s;
		while(bdp >=0){ // break multipart into parts
			bdp = s.indexOf(bd); // multi-part inital
			if(bdp >=0){
				ss = s.substring(bdp+bd.length()+1);
				bdp = ss.indexOf(bd); // multi-part end
				s = ss;
				if(bdp >=0){
					ss = ss.substring(0,bdp-2); // ss is now contents

					if(ss.indexOf("terminalId")<0){// ignore
						//						System.out.println(ss);
						saveAccFile(ss); // SaveAccCSVFile
					}
				}
			}
		}
		response.setContentType("text/plain");
		response.setStatus(HttpServletResponse.SC_OK);
	}

	public String getLine(String str,int offset){
		int end = str.indexOf("\n",offset);
		if( end >=0){
			return str.substring(offset,end);
		}else{
			return "";
		}
	}

	/* Save Acc File */
	void saveAccFile(String buffer){

		String disposition = getLine(buffer,0);
		// System.out.println("["+disposition+"]");
		ParameterParser parser = new ParameterParser();
		parser.setLowerCaseNames(true);
		// Parameter parser can handle null input
		Map params = parser.parse(disposition, new char[] {';', ','});
		String filename = (String) params.get("filename");
		String basename = filename.substring(0,filename.indexOf(".")-1);
		String accfilename = basename+"-acc"+".csv";
		String gyrofilename = basename+"-gyro"+".csv";
		String magfilename = basename+"-mag"+".csv";
		String locationfilename = basename+"-loc"+".csv";
		String metafilename = basename+".meta";

		System.out.println("Uploaded FileName: "+filename);
		int pos = disposition.length()+2;

		try {
			StringWriter labelFile = new StringWriter(); //basePath+File.separator+metafilename);
			StringWriter accFile = new StringWriter();//basePath+File.separator+filename);
			StringWriter gyroFile = new StringWriter();//basePath+File.separator+filename);
			StringWriter magFile = new StringWriter();//basePath+File.separator+filename);
			StringWriter locFile = new StringWriter();//basePath+File.separator+filename);
			String line = getLine(buffer,pos);
			boolean acc = false;
			boolean gyro = false;
			boolean mag = false;
			boolean loc = false;

			while(line.length() > 0){
				//System.out.println("["+line+"]");
				if(line.contains("ACC")){
					String dd[] = line.split("ACC\t");
					//System.out.println("("+dd[1]+")");
					if(dd.length >1){
						accFile.write(dd[1]+"\n");
						if(!acc)acc = true;
					}
				}else if(line.contains("GYRO")){
					String dd[] = line.split("GYRO\t");
					//System.out.println("("+dd[1]+")");
					if(dd.length >1){
						gyroFile.write(dd[1]+"\n");
						if(!gyro)gyro = true;
					}
				}else if(line.contains("MAG")){
					String dd[] = line.split("MAG\t");
					//System.out.println("("+dd[1]+")");
					if(dd.length >1){
						magFile.write(dd[1]+"\n");
						if(!mag)mag = true;
					}
				}else if(line.contains("LOC")){
					String dd[] = line.split("LOC\t");
					//System.out.println("("+dd[1]+")");
					if(dd.length >1){
						locFile.write(dd[1]+"\n");
						if(!loc)loc = true;
					}
				}else if(line.contains("TAGS")){
					String dd[] = line.split("TAGS\t");
					//					System.out.println("("+dd[1]+")");
					if(dd.length >1)
						labelFile.write("Tags: "+dd[1]+"\n");					
				}else if(line.contains("LOG_VERSION")){
					String dd[] = line.split("LOG_VERSION\t");
					//					System.out.println("("+dd[1]+")");
					if(dd.length >1)
						labelFile.write("LogVersion: "+dd[1]+"\n");					
				}else if(line.contains("TERMINAL_ID")){
					String dd[] = line.split("TERMINAL_ID\t");
					//					System.out.println("("+dd[1]+")");
					if(dd.length >1)
						labelFile.write("TerminalID: "+dd[1]+"\n");					
				}else if(line.contains("TERMINAL_TYPE")){
					String dd[] = line.split("TERMINAL_TYPE\t");
					//					System.out.println("("+dd[1]+")");
					if(dd.length >1)
						labelFile.write("TerminalType: "+dd[1]+"\n");					
				}else if(line.contains("COMMENT")){
					String dd[] = line.split("COMMENT\t");
					//					System.out.println("("+dd[1]+")");
					if(dd.length >1)
						labelFile.write("Comment: "+dd[1]+"\n");					
				}else{
					System.out.println("no output["+line+"]");
				}
				pos += line.length()+1;
				line = getLine(buffer,pos);
			}

			accFile.close();
			gyroFile.close();
			labelFile.close();

			// output for IDirectory
			if(acc)saveDataToResourceFile(accFile.toString(),accfilename);
			if(gyro)saveDataToResourceFile(gyroFile.toString(),gyrofilename);
			if(mag)saveDataToResourceFile(magFile.toString(),magfilename);
			if(loc)saveDataToResourceFile(locFile.toString(),locationfilename);
			saveDataToResourceFile(labelFile.toString(),metafilename);

		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}

	}

	void saveDataToResourceFile(String data,String fileName){
		try {
			ByteArrayInputStream bain=new ByteArrayInputStream(data.getBytes("UTF-8"));
			IFile outf = HascLoggerServer.getOutputBaseFolder().getFile(fileName);
			if (outf.exists()) {
				outf.setContents(bain, true, false, null);
			}else{
				outf.create(bain, true, null);
			}
			bain.close();
			System.out.println("wrote file:"+fileName);
		} catch (Exception ex) {
			throw new RuntimeException(ex);
		}
	}
}