package cn.net.connor.std.processedit.meopviewfx.ui;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.sql.Connection;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import com.teamcenter.rac.aif.kernel.AIFComponentContext;
import com.teamcenter.rac.aif.kernel.InterfaceAIFComponent;
import com.teamcenter.rac.kernel.TCComponent;
import com.teamcenter.rac.kernel.TCComponentDataset;
import com.teamcenter.rac.kernel.TCComponentFolder;
import com.teamcenter.rac.kernel.TCSession;
import com.teamcenter.rac.util.Registry;

import cn.net.connor.std.aifrcp.util.KSqlUtil;
import cn.net.connor.std.aifrcp.util.KUtil;
import cn.net.connor.std.processedit.meopviewfx.bean.TextBean;
import cn.net.connor.std.processedit.util.ProcessUtil;

public class TextTreeLoader {

	private static final String PREF_COMMON_FOLDER = "Connor_AVIC_GXBZ_Common_Folder";
	private static final String PREF_PERSONAL_FOLDER = "Connor_AVIC_GXBZ_Personal_Folder";
	private static final String FLAG_REALVALUE = "#RV#";
	private static final String PREFFLAG_REALVALUE = "#RealValue#";
	private static final Registry REG = Registry.getRegistry(TextTreeLoader.class);

	public static class FileBean {
		File file;
		int realValueCol;

		public FileBean(File file, int realValueCol) {
			this.file = file;
			this.realValueCol = realValueCol;
		}
	}

	private TCSession session;
	
	public TextTreeLoader(TCSession session) {
		this.session = session;
	}
	
	public Map<String, TextBean> loadText105() throws Exception {
		Map<String, TextBean> textMap = new LinkedHashMap<String, TextBean>();
		String key = REG.getString("mkhgy");
		String sql = "select pac5_JG1, pac5_JG2, pac5_JG3, pac5_JG4, pac5_JG5, pac5_JG6 from pAc5_MKHGYRevMasters";
		Connection conn = KSqlUtil.getOracleConnection(session, ProcessUtil.PREF_DB_CONN);
		List<String[]> data = null;
		int colCnt = 6;
		TextBean root = new TextBean(key);
		textMap.put(key, root);
		try {
			data = KSqlUtil.queryStringArray(conn, sql, null, colCnt);
		} finally {
			KSqlUtil.free(conn);
		}
		int cnt = data == null?0:data.size();
		for(int i=0; i<cnt ;i++) {
			String[] rowData = data.get(i);
			TextBean parent = root;
			for(int c=0; c<colCnt; c++) {
				String text = rowData[c];
				if(KUtil.isEmpty(text)) {
					break;
				}
				TextBean child = new TextBean(text);
				int ind = parent.children.indexOf(child);
				if(ind>=0) {
					parent = parent.children.get(ind);
				}else {
					parent.children.add(child);
					parent = child;
				}
			}
		}
		return textMap;
	}
	
	

	public Map<String, TextBean> loadText() throws Exception {
		Map<String, TextBean> textMap = new LinkedHashMap<String, TextBean>();
		List<FileBean> docFiles = getConfigFile();
		int size = docFiles.size();
		if (size == 0) {
			System.out.println("Special Text File not found");
			return textMap;
		}
		for (int i = 0; i < size; i++) {
			FileBean docFile = docFiles.get(i);
			System.out.println("Load File: " + docFile.file.getAbsolutePath());
			InputStream in = new FileInputStream(docFile.file);
			XSSFWorkbook wb = new XSSFWorkbook(in);
			in.close();
			int sheetCnt = wb.getNumberOfSheets();
			for (int j = 0; j < sheetCnt; j++) {
				XSSFSheet sheet = wb.getSheetAt(0);
				String sheetName = sheet.getSheetName();
				System.out.println(">> Load Sheet: " + sheetName);
				if (textMap.containsKey(sheetName)) {
					System.out.println("SKIP");
					continue;
				}
				TextBean bean = readSheet(sheet, docFile.realValueCol);
				if (bean != null && bean.children.size() > 0) {
					textMap.put(sheetName, bean);
				} else {
					System.out.println("No Data");
				}
			}
		}
		return textMap;
	}

	private TextBean readSheet(XSSFSheet sheet, int realValueCol) throws Exception {
		TextBean root = new TextBean(sheet.getSheetName());
		int firstRow = sheet.getFirstRowNum();
		int lastRow = sheet.getLastRowNum();
		Map<Integer, TextBean> parents = new HashMap<Integer, TextBean>();
		parents.put(0, root);
		for (int i = firstRow; i <= lastRow; i++) {
			XSSFRow row = sheet.getRow(i);
			if (row == null) {
				continue;
			}
			int firstCol = row.getFirstCellNum();
			if (firstCol < 0) {
				firstCol = 0;
			}
			int lastCol = row.getLastCellNum();
			for (int j = firstCol; j <= lastCol; j++) {
				XSSFCell cell = row.getCell(j);
				if (cell == null || cell.getCellType() != XSSFCell.CELL_TYPE_STRING) {
					continue;
				}
				if (!parents.containsKey(j)) {
					continue;
				}
				String text = cell.getStringCellValue();
				if (KUtil.isEmpty(text)) {
					continue;
				}
				if (j == realValueCol) {
					parents.get(j).setRealValue(text);
					continue;
				}
				if (text.startsWith(FLAG_REALVALUE)) {
					parents.get(j).setRealValue(text.substring(FLAG_REALVALUE.length()));
					continue;
				}
				TextBean bean = new TextBean(text);
				// for(int k=j+1;k<=lastCol;k++) {
				// XSSFCell realValueCell = row.getCell(k);
				// if(realValueCell!=null&&realValueCell.getCellType()==XSSFCell.CELL_TYPE_STRING)
				// {
				// String realValue = realValueCell.getStringCellValue();
				// if(!KUtil.isEmpty(realValue)) {
				// bean.setRealValue(realValue);
				// break;
				// }
				// }
				// }
				parents.get(j).children.add(bean);
				parents.put(j + 1, bean);
				// break;
			}
		}
		return root;
	}

	protected List<FileBean> getConfigFile() {
		List<FileBean> files = new ArrayList<>();
		try {
			addFileFromPref(files, PREF_COMMON_FOLDER, "");
		} catch (Exception e) {
			System.out.println("Load Text Tree From <" + PREF_COMMON_FOLDER + "> Error");
			e.printStackTrace();
		}
		try {
			addFileFromPref(files, PREF_PERSONAL_FOLDER, session.getUser().getUserId());
		} catch (Exception e) {
			System.out.println("Load Text Tree From <" + PREF_PERSONAL_FOLDER + "> Error");
			e.printStackTrace();
		}
		return files;
	}

	private void addFileFromPref(List<FileBean> files, String prefName, String subFolder) throws Exception {
		String uid = KUtil.getPrefVal(session, prefName);
		if (KUtil.isEmpty(uid)) {
			return;
		}
		int realValueColumn = -1;
		int ind = uid.indexOf(PREFFLAG_REALVALUE);
		if (ind > 0) {
			String numStr = uid.substring(ind + PREFFLAG_REALVALUE.length());
			uid = uid.substring(0, ind);
			try {
				realValueColumn = Integer.parseInt(numStr);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		TCComponent comp = session.stringToComponent(uid);
		if (comp == null) {
			return;
		}
		if (comp instanceof TCComponentFolder) {
			TCComponentFolder folder = (TCComponentFolder) comp;
			AIFComponentContext[] children = folder.getChildren();
			if (!KUtil.isEmpty(subFolder)) {
				for (AIFComponentContext c : children) {
					InterfaceAIFComponent child = c.getComponent();
					if (child instanceof TCComponentFolder) {
						if (subFolder.equals(((TCComponentFolder) child).getStringProperty("object_name"))) {
							children = child.getChildren();
							break;
						}
					}
				}
			}
			for (AIFComponentContext c : children) {
				InterfaceAIFComponent child = c.getComponent();
				if ("MSExcelX".equals(child.getType())) {
					File[] dbFiles = ((TCComponentDataset) child).getFiles("");
					if (dbFiles != null) {
						for (int i = 0; i < dbFiles.length; i++) {
							files.add(new FileBean(dbFiles[i], realValueColumn));
						}
					}
				}
			}
		} else if (comp instanceof TCComponentDataset) {
			TCComponentDataset dataset = (TCComponentDataset) comp;
			if ("MSExcelX".equals(dataset.getType())) {
				File[] dbFiles = dataset.getFiles("");
				if (dbFiles != null) {
					for (int i = 0; i < dbFiles.length; i++) {
						files.add(new FileBean(dbFiles[i], realValueColumn));
					}
				}
			}
		}
	}

}
