package cn.net.connor.std.processedit.modifymeopno;

import java.util.Arrays;

import com.teamcenter.rac.aif.kernel.AIFComponentContext;
import com.teamcenter.rac.aif.kernel.InterfaceAIFComponent;
import com.teamcenter.rac.kernel.TCComponentBOMLine;
import com.teamcenter.rac.kernel.TCComponentItemRevision;
import com.teamcenter.rac.kernel.TCException;
import com.teamcenter.rac.util.Registry;

import cn.net.connor.std.aifrcp.KDialogController;
import cn.net.connor.std.aifrcp.util.KUtil;
import cn.net.connor.std.processedit.util.ProcessUtil;

public class ModifyMeopNoDialogController extends KDialogController {

	public static final Registry REG = Registry.getRegistry(ModifyMeopNoDialogController.class);
	public static final String PREF_MEOP_TYPE = "Connor_AVIC_SQGXH_GXLX";
	public static final String PREF_MEOP_TABLE = "Connor_AVIC_SQGXH_SXBJ";
	private String[] meopTypes;
	protected String[] tableHeaders;
	protected int[] tableHeaderWidth;
	private String[] tableProps;
	private ModifyMeopNoDialog dialog;
	private TCComponentBOMLine procLine;
	private TCComponentItemRevision targetRev;

	@Override
	public boolean init() throws Exception {
		this.dialog = (ModifyMeopNoDialog) aifDialog;
		InterfaceAIFComponent comp = app.getTargetComponent();
		System.out.println("Select: " + comp);
		if (comp != null) {
			if (comp instanceof TCComponentBOMLine) {
				this.procLine = (TCComponentBOMLine) comp;
				TCComponentItemRevision rev = this.procLine.getItemRevision();
				System.out.println(">> " + rev.getType());
				if (ProcessUtil.isMEProcess(session, rev.getItem().getType())) {
					// if (rev instanceof TCComponentMEProcessRevision) {
					this.targetRev = rev;
				}
			}
		}
		if (targetRev == null) {
			throw new TCException(REG.getString("selectprocessrev.ERROR"));
		}
		this.meopTypes = KUtil.getPrefVals(session, PREF_MEOP_TYPE);
		String[] tableConfigs = KUtil.getPrefVals(session, PREF_MEOP_TABLE);
		if (KUtil.getLen(meopTypes) == 0) {
			throw new TCException(String.format(REG.getString("prefnotconfiged.ERROR1"), PREF_MEOP_TYPE));
		}
		if (KUtil.getLen(tableConfigs) == 0) {
			throw new TCException(String.format(REG.getString("prefnotconfiged.ERROR1"), PREF_MEOP_TABLE));
		}
		int colCnt = KUtil.getLen(tableConfigs);
		tableHeaders = new String[colCnt + 1];
		tableHeaderWidth = new int[colCnt + 1];
		tableHeaders[0] = "Hidden";
		tableHeaderWidth[0] = 0;
		tableProps = new String[colCnt];
		for (int i = 0; i < colCnt; i++) {
			int colIndex = i + 1;
			String config = tableConfigs[i];
			int ind = config.lastIndexOf('=');
			if (ind > 0) {
				tableHeaders[colIndex] = config.substring(0, ind);
				tableProps[i] = config.substring(ind + 1);
			} else {
				tableHeaders[colIndex] = config;
				tableProps[i] = config;
			}
			int width = 0;
			while (tableHeaders[colIndex].length() > 0 && Character.isDigit(tableHeaders[colIndex].charAt(0))) {
				width = width * 10 + (tableHeaders[colIndex].charAt(0) - '0');
				tableHeaders[colIndex] = tableHeaders[colIndex].substring(1);
			}
			if (width < 1) {
				width = 120;
			}
			tableHeaderWidth[colIndex] = width;
		}
		return true;
	}

	protected void readMeop() throws Exception {
		System.out.println("Load Meop: " + this.procLine + " | " + Arrays.toString(meopTypes));
		if (this.procLine == null) {
			return;
		}
		KUtil.setByPassItk(session, true);
		try {
			this.procLine.refresh();
			AIFComponentContext[] cc = this.procLine.getChildren();
			int len = KUtil.getLen(cc);
			for (int i = 0; i < len; i++) {
				TCComponentBOMLine cLine = (TCComponentBOMLine) cc[i].getComponent();
				String cType = cLine.getItem().getType();
				System.out.println((i + 1) + ". " + cLine + " -> " + cType);
				if (KUtil.inArray(cType, meopTypes) >= 0) {
					dialog.tableModel.addRow(new ModifyMeopNoRow(cLine).getRowData(tableProps));
				}
			}
		} finally {
			KUtil.setByPassItk(session, false);
		}
	}

	public void delete() throws Exception {
		int selectedRow = dialog.table.getSelectedRow();
		System.out.println("Delete: " + selectedRow);
		if (selectedRow < 0) {
			return;
		}
		ModifyMeopNoRow bean = (ModifyMeopNoRow) dialog.table.getValueAt(selectedRow, 0);
		TCComponentBOMLine bomline = bean.getBomline();
		System.out.println("Remove Line: " + bomline);
		KUtil.setByPassItk(session, true);
		try {
//			int currentSeq = NewMeopDialogController.getMeopNo(bomline);
//			System.out.println("Current Seq: " + currentSeq);
			bomline.cut();
			dialog.tableModel.removeRow(selectedRow);
//			if (checkSeq(currentSeq)) {
//				int rowCnt = dialog.table.getRowCount();
//				for (int i = selectedRow; i < rowCnt; i++) {
//					bean = (ModifyMeopNoRow) dialog.table.getValueAt(i, 0);
//					bomline = bean.getBomline();
//					bomline.refresh();
//					int seq = NewMeopDialogController.getMeopNo(bomline);
//					// int seq = Integer.parseInt(bomline.getStringProperty("bl_sequence_no"));
//					System.out.println("Change Sequence: " + bomline + " " + seq + " -> " + (seq - 5));
//					seq -= 5;
//					NewMeopDialogController.setMeopNo(bomline, seq);
//					// bomline.setProperty("bl_sequence_no", "" + seq);
//					bomline.refresh();
//					dialog.tableModel.removeRow(i);
//					dialog.tableModel.insertRow(i, bean.getRowData(tableProps));
//				}
//			} else {
//				System.out.println("Skip Change");
//			}
			procLine.refresh();
		} finally {
			KUtil.setByPassItk(session, false);
		}
		checkRelease();
	}

	public boolean checkSeq(int seq) {
		return seq > 0 && seq % 5 == 0;
	}

	public void checkRelease() {
		int rowCnt = dialog.table.getRowCount();
		boolean hasRelease = false;
		for (int i = 0; i < rowCnt; i++) {
			if (((ModifyMeopNoRow) dialog.table.getValueAt(i, 0)).isReleased()) {
				hasRelease = true;
				break;
			}
		}
		dialog.b_moveup.setEnabled(!hasRelease);
		dialog.b_movedown.setEnabled(!hasRelease);
	}

	public void moveup() throws Exception {
		int selectedRow = dialog.table.getSelectedRow();
		System.out.println("Move Up: " + selectedRow);
		if (selectedRow <= 0) {
			return;
		}

		KUtil.setByPassItk(session, true);
		try {
			ModifyMeopNoRow bean = (ModifyMeopNoRow) dialog.table.getValueAt(selectedRow, 0);
			TCComponentBOMLine bomline = bean.getBomline();
			System.out.println("Select Line: " + bomline);
			ModifyMeopNoRow otherbean = (ModifyMeopNoRow) dialog.table.getValueAt(selectedRow - 1, 0);
			TCComponentBOMLine otherBomline = otherbean.getBomline();
			System.out.println("Other Line: " + otherBomline);
			int blseq = Integer.parseInt(bomline.getStringProperty("bl_sequence_no"));
			int otherblSeq = Integer.parseInt(otherBomline.getStringProperty("bl_sequence_no"));
			bomline.setProperty("bl_sequence_no", otherblSeq + "");
			otherBomline.setProperty("bl_sequence_no", blseq + "");
//			int seq = NewMeopDialogController.getMeopNo(bomline);
//			int otherSeq = NewMeopDialogController.getMeopNo(otherBomline);
//			if (checkSeq(seq) && checkSeq(otherSeq)) {
//				NewMeopDialogController.setMeopNo(bomline, otherSeq);
//				NewMeopDialogController.setMeopNo(otherBomline, seq);
//			} else {
//				System.out.println("Skip Change");
//			}
			bomline.refresh();
			otherBomline.refresh();
			procLine.refresh();
			dialog.tableModel.removeRow(selectedRow);
			dialog.tableModel.removeRow(selectedRow - 1);
			dialog.tableModel.insertRow(selectedRow - 1, otherbean.getRowData(tableProps));
			dialog.tableModel.insertRow(selectedRow - 1, bean.getRowData(tableProps));
			dialog.table.getSelectionModel().setSelectionInterval(selectedRow - 1, selectedRow - 1);
		} finally {
			KUtil.setByPassItk(session, false);
		}
	}

	public void movedown() throws Exception {
		int selectedRow = dialog.table.getSelectedRow();
		System.out.println("Move Down: " + selectedRow);
		int rowCnt = dialog.table.getRowCount();
		if (selectedRow < 0 || selectedRow == rowCnt - 1) {
			return;
		}
		KUtil.setByPassItk(session, true);
		try {
			ModifyMeopNoRow bean = (ModifyMeopNoRow) dialog.table.getValueAt(selectedRow, 0);
			TCComponentBOMLine bomline = bean.getBomline();
			System.out.println("Select Line: " + bomline);
			ModifyMeopNoRow otherbean = (ModifyMeopNoRow) dialog.table.getValueAt(selectedRow + 1, 0);
			TCComponentBOMLine otherBomline = otherbean.getBomline();
			System.out.println("Other Line: " + otherBomline);
			int blseq = Integer.parseInt(bomline.getStringProperty("bl_sequence_no"));
			int otherblSeq = Integer.parseInt(otherBomline.getStringProperty("bl_sequence_no"));
			bomline.setProperty("bl_sequence_no", otherblSeq + "");
			otherBomline.setProperty("bl_sequence_no", blseq + "");
//			int seq = NewMeopDialogController.getMeopNo(bomline);
//			int otherSeq = NewMeopDialogController.getMeopNo(otherBomline);
//			if (checkSeq(seq) && checkSeq(otherSeq)) {
//				NewMeopDialogController.setMeopNo(bomline, otherSeq);
//				NewMeopDialogController.setMeopNo(otherBomline, seq);
//			} else {
//				System.out.println("Skip Change");
//			}
			bomline.refresh();
			otherBomline.refresh();
			procLine.refresh();
			dialog.tableModel.removeRow(selectedRow + 1);
			dialog.tableModel.removeRow(selectedRow);
			dialog.tableModel.insertRow(selectedRow, bean.getRowData(tableProps));
			dialog.tableModel.insertRow(selectedRow, otherbean.getRowData(tableProps));
			dialog.table.getSelectionModel().setSelectionInterval(selectedRow + 1, selectedRow + 1);
		} finally {
			KUtil.setByPassItk(session, false);
		}
	}

}
