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

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.nio.charset.Charset;
import java.util.Arrays;

import org.apache.commons.io.IOUtils;

import cokr.xit.fims.FimsConf;
import cokr.xit.foundation.data.DataObject;
import net.minidev.json.JSONArray;
import net.minidev.json.JSONObject;
import net.minidev.json.parser.JSONParser;

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

	@Override
	public void analyzeFileContent(DataObject dataObject, File file) {
		try {
			JSONArray jsonArray = (JSONArray)new JSONParser(-1).parse(descriptor.getContentItems());
			boolean isMetaData = "TXT".equalsIgnoreCase(dataObject.string("FILE_EXTENSION"));
			if (isMetaData) {
				BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(file),Charset.forName(ifEmpty(FimsConf.get().getTxtCharset(), "UTF-8"))));
				String content = IOUtils.toString(br);
				String[] contentDivision = null;
				String part = "";
				int contentDivisionIndex = 0;
				int partSplitCursor = 0;

				if (!descriptor.getContentSecondSeperator().isEmpty()) {
					contentDivision = this.smartSplit(content, descriptor.getContentSecondSeperator());
					part = contentDivision[contentDivisionIndex];
				} else {
					part = content;
				}

				for (int i = 0; i < jsonArray.size(); i++) {
					JSONObject jsonObject = (JSONObject)jsonArray.get(i);
					String key = jsonObject.keySet().iterator().next();

					if (Arrays.asList(descriptor.getSecondSeperatorStarterItems().split(",",-1)).contains(key)) {
						contentDivisionIndex++;
						partSplitCursor = 0;
						if (contentDivision.length > contentDivisionIndex) {
							part = contentDivision[contentDivisionIndex];
						} else {
							part = "";
						}
					}

					String[] partSplit = this.smartSplit(part, descriptor.getContentSeperator());

					if (partSplit.length > partSplitCursor) {
						dataObject.put(key, partSplit[partSplitCursor]);
					} else {
						dataObject.put(key, "");
					}
					partSplitCursor++;
				}
				br.close();
	    	} else {
	    		for (int i = 0; i < jsonArray.size(); i++) {
					JSONObject jsonObject = (JSONObject)jsonArray.get(i);
					String key = jsonObject.keySet().iterator().next();
					dataObject.put(key, "");
				}
	    	}
		} catch (Exception e) {
			throw runtimeException(e);
		}
	}
}