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

import java.util.Arrays;
import java.util.List;

import org.eclipse.ui.IViewPart;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.IWorkbenchWindow;
import org.eclipse.ui.internal.e4.compatibility.CompatibilityView;

import com.teamcenter.rac.aif.AbstractAIFApplication;
import com.teamcenter.rac.aif.kernel.InterfaceAIFComponent;
import com.teamcenter.rac.aifrcp.AIFUtility;
import com.teamcenter.rac.cme.application.MFGLegacyApplication;
import com.teamcenter.rac.cme.framework.treetable.CMEBOMTreeTable;
import com.teamcenter.rac.cme.framework.views.primary.BOMPrimaryView;
import com.teamcenter.rac.kernel.TCComponent;
import com.teamcenter.rac.kernel.TCComponentBOMLine;
import com.teamcenter.rac.kernel.TCComponentBOMWindow;
import com.teamcenter.rac.kernel.TCComponentCfgAttachmentLine;
import com.teamcenter.rac.kernel.TCComponentDataset;
import com.teamcenter.rac.kernel.TCComponentItemRevision;
import com.teamcenter.rac.kernel.TCException;
import com.teamcenter.rac.util.MessageBox;
import com.teamcenter.rac.util.PlatformHelper;
import com.teamcenter.rac.util.Registry;

import cn.net.connor.std.aifrcp.KOperation;
import cn.net.connor.std.aifrcp.util.KUtil;

@SuppressWarnings("restriction")
public class NewDatasetFromTemplateOperation extends KOperation {

	public static final Registry REG = Registry.getRegistry(NewDatasetFromTemplateOperation.class);
	private String prefName;
	private TCComponentDataset template;
	private String[] selectTypes;
	private String relation;
	private String nameConfig;
	private String successAlert;
	private String existAlert;
	private TCComponentItemRevision targetRev;
	private TCComponentBOMLine targetBOMLine;
	private boolean refreshCfgLines = false;

	public NewDatasetFromTemplateOperation(AbstractAIFApplication app, String prefName) {
		super(app, REG.getString("op.Name"));
		this.prefName = prefName;
	}

	@Override
	public boolean init() throws Exception {
		String[] prefValues = KUtil.getPrefVals(session, prefName);
		System.out.println("NewDatasetFromTemplateOperation");
		System.out.println(prefName + " -> " + Arrays.toString(prefValues));
		int prefCnt = KUtil.getLen(prefValues);
		/**
		 * select=select type relation=relation name=dataset name success=success alert
		 * dataset=uid exist=exist alert
		 */
		for (int i = 0; i < prefCnt; i++) {
			String pref = prefValues[i];
			int ind = pref.indexOf('=');
			if (ind <= 0) {
				continue;
			}
			String key = pref.substring(0, ind).trim().toLowerCase();
			String value = pref.substring(ind + 1);
			switch (key) {
			case "select":
				this.selectTypes = value.split(";");
				break;
			case "relation":
				this.relation = value;
				break;
			case "name":
				this.nameConfig = value;
				break;
			case "success":
				this.successAlert = value;
				break;
			case "dataset":
				String uid = value;
				try {
					this.template = (TCComponentDataset) session.stringToComponent(uid);
				} catch (TCException e) {
					e.printStackTrace();
				}
				break;
			case "exist":
				this.existAlert = value;
				break;

			default:
				break;
			}
		}
		System.out.println("Template: " + this.template);
		if (this.template == null || KUtil.getLen(this.selectTypes) == 0 || KUtil.isEmpty(this.relation) || KUtil.isEmpty(this.nameConfig)) {
			throw new TCException(String.format(REG.getString("pref.Error1"), prefName));
		}
		InterfaceAIFComponent target = app.getTargetComponent();
		if (target != null) {
			if (target instanceof TCComponentBOMLine) {
				this.targetBOMLine = (TCComponentBOMLine) target;
				this.targetRev = targetBOMLine.getItemRevision();
			} else if (target instanceof TCComponentCfgAttachmentLine) {
				TCComponent obj = ((TCComponentCfgAttachmentLine) target).getUnderlyingComponent();
				if (obj != null && (obj instanceof TCComponentItemRevision)) {
					this.targetRev = (TCComponentItemRevision) obj;
					this.refreshCfgLines = true;
				}
			}
		}
		if (refreshCfgLines) {
			TCComponentBOMWindow bomWindow = ((TCComponentCfgAttachmentLine) target).window().getBomWindow();
			System.out.println(">> BomWindow: " + bomWindow);
			System.out.println(">> " + app.getClass());
			if (app instanceof MFGLegacyApplication) {
				List<Object> viewParts = PlatformHelper.getAllViewParts();
				IWorkbenchWindow var1 = AIFUtility.getActiveDesktop().getDesktopWindow();
				IWorkbenchPage page = var1.getActivePage();
				for (Object viewPart : viewParts) {
					if (viewPart == null || !(viewPart instanceof CompatibilityView)) {
						continue;
					}
					IViewPart view = ((CompatibilityView) viewPart).getView();
					if (view == null || !(view instanceof BOMPrimaryView)) {
						continue;
					}

					BOMPrimaryView bomView = (BOMPrimaryView) view;
					CMEBOMTreeTable treeTable = bomView.getBOMTreeTable();
					if (treeTable == null) {
						continue;
					}
					boolean visible = page.isPartVisible(view);
					System.out.println(">> BOMPrimaryView: [" + visible + "]" + bomView);
					if (!visible) {
						continue;
					}
					if (treeTable.getBOMWindow() == bomWindow) {
						System.out.println(">>>>> find window");
						TCComponentBOMLine[] bomlines = treeTable.getSelectedBOMLines();
						System.out.println(">> Selected lines: " + Arrays.toString(bomlines));
						int bomLineCnt = KUtil.getLen(bomlines);
						if (bomLineCnt == 1 && this.targetRev == bomlines[0].getItemRevision()) {
							this.targetBOMLine = bomlines[0];
							System.out.println(">>>>> Find targetline");
							break;
						}
					}
				}
			}
		}
		String targetType = this.targetRev == null ? "" : this.targetRev.getType();
		System.out.println("Select " + target + " [" + targetType + "]");
		if (KUtil.isEmpty(targetType) || KUtil.inArray(targetType, selectTypes) < 0) {
			String[] typeNames = new String[this.selectTypes.length];
			for (int i = 0; i < this.selectTypes.length; i++) {
				typeNames[i] = KUtil.getTypeName(session, this.selectTypes[i]);
			}
			throw new TCException(String.format(REG.getString("select.Error1"), Arrays.toString(typeNames)));
		}
		if (this.targetBOMLine == null) {
			throw new TCException(REG.getString("nobomline.Error"));
		}
		return true;
	}

	@SuppressWarnings("deprecation")
	@Override
	public void execute() throws Exception {
		this.targetRev.refresh();
		this.targetBOMLine.refresh();
		String dsName = KUtil.getPropValueByPath(targetBOMLine, nameConfig, "-");
		System.out.println("Dataset Name: " + dsName);
		if (!KUtil.isEmpty(this.existAlert)) {
			TCComponent existDataset = KUtil.getChildByTypeAndName(targetRev, template.getType(), dsName, relation);
			System.out.println("Exist: " + existDataset);
			if (existDataset != null) {
				MessageBox.post(existAlert, "", MessageBox.WARNING);
				return;
			}
		}
		TCComponentDataset newDataset = this.template.saveAs(dsName);
		System.out.println("New Dataset: " + newDataset);
		if (newDataset == null) {
			throw new TCException(REG.getString("saveas.Error"));
		}
		this.targetRev.add(relation, newDataset);
		this.targetRev.refresh();
		// rename file ref
		TCComponent[] refs = newDataset.getReferenceListProperty("ref_list");
		if (KUtil.getLen(refs) > 0) {
			TCComponent ref = refs[0];
			String fileName = ref.getStringProperty("original_file_name");
			System.out.println("Check file name: " + fileName);
			int ind = fileName.lastIndexOf('.');
			if (ind > 0) {
				String ext = fileName.substring(ind);
				String newName = dsName;
				if (!newName.toLowerCase().endsWith(ext.toLowerCase())) {
					newName += ext;
				}
				ref.lock();
				try {
					ref.setStringProperty("original_file_name", newName);
					ref.save();
				} finally {
					ref.refresh();
				}
			}
		}
		if (!KUtil.isEmpty(this.successAlert)) {
			MessageBox.post(successAlert, "", MessageBox.INFORMATION);
		}
		session.refreshComponentsByType("CfgBlAttachmentLine");
	}

	@Override
	public void clearCache() throws Exception {

	}

}
