package cn.com.origin.autocode.newitem.origin;

import java.awt.Toolkit;
import java.awt.datatransfer.StringSelection;
import cn.com.origin.autocode.newitem.generatcode.NewCodeItemDialog;
import cn.com.origin.autocodemanager.common.AutoCodeManagerPropertyName;
import cn.com.origin.autocodemanager.common.TCPreferenceUitl;
import com.teamcenter.rac.aifrcp.AifrcpPlugin;
import com.teamcenter.rac.kernel.TCAttribute;
import com.teamcenter.rac.kernel.TCClass;
import com.teamcenter.rac.kernel.TCComponent;
import com.teamcenter.rac.kernel.TCComponentItem;
import com.teamcenter.rac.kernel.TCComponentItemRevision;
import com.teamcenter.rac.kernel.TCException;
import com.teamcenter.rac.kernel.TCProperty;
import com.teamcenter.rac.kernel.TCSession;

public class ORAfterNewItemCustomization {
	private TCSession session;

	public ORAfterNewItemCustomization(NewCodeItemDialog newCodeItemDialog, TCComponent newComponent) {
		getSession();
		saveIsLockProperty(newComponent, "true");
	}

//	public ORAfterNewItemCustomization(
//			NewCodeItemDialogNew newCodeItemDialogNew, TCComponent newComp) {
//		// TODO Auto-generated constructor stub
//	}

	public TCSession getSession() {
		if (session == null)
			session = (TCSession) AifrcpPlugin.getSessionService().getDefaultSession();
		return session;
	}

	private void saveIsLockProperty(TCComponent newComp, String value) {
		try {
			if (TCPreferenceUitl.isSelectExsitToTCPreferenceValues(session, "origin_newItem_isLock", newComp.getType())) {
				TCClass tcclass = newComp.getTCClass();
				saveAttributeValue(newComp, tcclass, AutoCodeManagerPropertyName.Item_isLock, value);
			}
			if (TCPreferenceUitl.isSelectExsitToTCPreferenceValues(session, "origin_newItemRev_isLock", newComp.getType())) {
				TCComponentItemRevision itemRev = ((TCComponentItem) newComp).getLatestItemRevision();
				TCProperty rev_isLock = itemRev.getTCProperty(AutoCodeManagerPropertyName.ItemRevision_isLock);
				if (rev_isLock != null) {
					itemRev.setProperty(AutoCodeManagerPropertyName.ItemRevision_isLock, value);
				}
			}
		} catch (TCException e) {
			e.printStackTrace();
		}
	}

	private void saveAttributeValue(TCComponent newComp, TCClass tcclass, String attributeName, String value) {
		try {
			tcclass = newComp.getTCClass();
			TCAttribute tccattribute = tcclass.findTCAttribute(attributeName);
			if (tccattribute != null) {
				newComp.setProperty(attributeName, value);
			}
		} catch (TCException e) {
			e.printStackTrace();
		}
	}

	public void setClipboard(String str) {
		try {
			if (!"".equals(str)) {
				StringSelection ss = new StringSelection(str);
				Toolkit.getDefaultToolkit().getSystemClipboard().setContents(ss, null);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

}
