package cokr.xit.fims.crdn.receive.eqpmnt;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.Charset;
import java.util.Base64;
import java.util.Base64.Decoder;
import java.util.Base64.Encoder;

import cokr.xit.applib.Hangul;
import cokr.xit.base.file.FileInfo;
import cokr.xit.foundation.data.DataObject;
import net.minidev.json.JSONArray;
import net.minidev.json.JSONObject;
import net.minidev.json.parser.JSONParser;

public class SingleFileParser extends LayoutParser {
	public SingleFileParser(){
		super();
		this.groupingType = "BIN";
		this.need = new Need(false,true,false);
	}

	/**파일내용을 분석한다.<br />
	 * @param dataObject
	 * @return
	 */
	@Override
	public void analyzeFileContent(DataObject dataObject, File file) {
		try {
			JSONParser jsonParser = new JSONParser(-1);

			JSONArray jsonArray = (JSONArray)jsonParser.parse(descriptor.getContentItems());

			//텍스트 영역 파싱
	    	BufferedReader textReader = new BufferedReader(new InputStreamReader(new FileInputStream(file), Charset.forName("EUC-KR")));
	    	Hangul hangul = new Hangul(2);
	    	String textConent = hangul.substringByBytes(org.apache.commons.io.IOUtils.toString(textReader), 1, this.getSumByte(jsonArray));

			String[] contentSplit = {};

			if(descriptor.getContentSeperator().equals("byte")) {
				contentSplit = this.smartSplit(textConent, jsonArray);
			} else {
				contentSplit = this.smartSplit(textConent, descriptor.getContentSeperator());
			}

			for(int i=0; i<jsonArray.size(); i++) {

				JSONObject jsonObject = (JSONObject)jsonArray.get(i);

				String key = jsonObject.keySet().iterator().next();

				if(contentSplit.length > i) {
					dataObject.put(key, contentSplit[i]);
				} else {
					dataObject.put(key, "");
				}
			}

			textReader.close();

			//이미지 영역 파싱
			BufferedReader imageReader = new BufferedReader(new InputStreamReader(new FileInputStream(file), Charset.forName("ISO-8859-1")));

			String imgContent = org.apache.commons.io.IOUtils.toString(imageReader).substring(this.getSumByte(jsonArray));

	    	Encoder encoder = Base64.getEncoder();

	    	String jpgString = "";
	    	String jpgName = "";
	    	boolean jpgIn = false;
	    	int jpgNum = 0;
	    	String jpgNamePiece = "";

	    	for (int i = 0; i < imgContent.length(); i++) {
	    		boolean jpgStart = (i != imgContent.length()-1) && (imgContent.charAt(i) == 0xFF && imgContent.charAt(i+1) == 0xD8);
	    		boolean jpgEnd = (i != 0) && (imgContent.charAt(i-1) == 0xFF && imgContent.charAt(i) == 0xD9);

	    		if(!jpgIn && !jpgStart) {
	    			jpgNamePiece += imgContent.charAt(i);
	    		}

	    		if(jpgStart) {
	    			jpgName = jpgNamePiece;
	    			jpgNamePiece = "";
	    			jpgIn = true;
	    		}

	    		if(jpgIn) {
	    			jpgString += imgContent.charAt(i);
	    		}

	    		if(jpgIn && jpgEnd) {
	    			jpgNum++;

	    			jpgString = new String(encoder.encode(jpgString.getBytes(Charset.forName("ISO-8859-1"))));

	        		dataObject.put("B64IMAGE"+(jpgNum), jpgString);
	        		dataObject.put("B64IMAGE"+(jpgNum)+"_NM", jpgName);

	        		jpgString = "";
	        		jpgIn = false;
	    		}

	        }
	    	imageReader.close();
    	} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}

	/** 베이스64문자열 이미지로 fileInfo를 생성한다. <br />
	 * @param fileName 파일명, base64str 베이스64문자열, sortOrder 파일순서
	 * @return fileInfo 파일정보
	 */
	public static FileInfo base64ToFileInfo(String fileName, String base64str, int sortOrder) {
		try {
			Decoder decoder = Base64.getDecoder();
			byte[] b64byte = decoder.decode(base64str.getBytes("ISO-8859-1"));
			InputStream is = new ByteArrayInputStream(b64byte);

			FileInfo fileInfo = new FileInfo();
			fileInfo.setName(fileName+".jpg");
			fileInfo.setInputStream(is);
			fileInfo.setMimeType("image/jpeg");
			fileInfo.setSize(is.available());
			fileInfo.setSortOrder(sortOrder);
			return fileInfo;
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}
}