package com.teamcenter.rac.viewer.stylesheet.beans;

import cn.com.origin.autocode.newitem.newcode.NewCodeItemDialog;
import cn.com.origin.autocodemanager.common.PackCodeDescInfos;
import com.teamcenter.rac.aif.AIFDesktop;
import com.teamcenter.rac.commands.newitem.NamingRulesHelper;
import com.teamcenter.rac.common.Activator;
import com.teamcenter.rac.kernel.TCComponentType;
import com.teamcenter.rac.kernel.TCException;
import com.teamcenter.rac.kernel.TCProperty;
import com.teamcenter.rac.kernel.TCPropertyDescriptor;
import com.teamcenter.rac.kernel.TCSession;
import com.teamcenter.rac.kernel.TCTextService;
import com.teamcenter.rac.services.ISessionService;
import com.teamcenter.rac.util.Registry;
import com.teamcenter.rac.util.controls.SWTComboBox;
import com.teamcenter.rac.util.controls.TextControl;
import com.teamcenter.services.rac.core.DataManagementService;
import com.teamcenter.soa.client.model.NamingRule;
import java.util.Map;
import org.apache.log4j.Logger;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Text;
import org.eclipse.ui.forms.widgets.FormToolkit;

// Referenced classes of package com.teamcenter.rac.viewer.stylesheet.beans:
//            AbstractPropertyBean, TextfieldPropertyBean, AbstractAutoAssignBean

public class CUSTAutoAssignItemIDPropertyBean extends AbstractPropertyBean
{
    private class IC_GenerateIDButtonSelectionAdapter extends SelectionAdapter
    {

        public void widgetSelected(SelectionEvent selectionevent)
        {
            try
            {
                String itemType = getOwningTypeName(m_propDesc);
                Composite composite = m_propBean.getControl().getParent().getParent();
                textObject_name = getSession().getTextService().getTextValue(object_name);
                textObject_desc = getSession().getTextService().getTextValue(object_desc);
                textObject_rev1 = getSession().getTextService().getTextValue(revision_id1);
                getNameTextByLabel(composite, object_name);
                if(itemNameText == null)
                    getNameTextByLabel(composite, textObject_name);
                getNameTextByLabel(composite, object_desc);
                if(itemDescText == null)
                    getNameTextByLabel(composite, textObject_desc);
                getNameTextByLabel(composite, revision_id1);
                if(itemRevText == null)
                    getNameTextByLabel(composite, textObject_rev1);
                if(itemRevText == null)
                {
                    getNameTextByLabel(composite, revision_id2);
                    if(itemRevText == null)
                        getNameTextByLabel(composite, textObject_rev2);
                }
                if(m_propBean instanceof TextfieldPropertyBean)
                {
                    TextfieldPropertyBean textfieldPropertyBean = (TextfieldPropertyBean)m_propBean;
                    itemIDText = textfieldPropertyBean.getTextField();
                }
//                itemType = itemType.replace("°æ±¾", "").replace("Revision", "");
//                System.out.println("CECAutoAssignItemIDPropertyBean itemType = "+itemType);
                PackCodeDescInfos packCodeDescInfos = new PackCodeDescInfos();
//                (new NewCodeItemDialog(AIFDesktop.getActiveDesktop().getShell(), itemType, packCodeDescInfos)).open();
                (new NewCodeItemDialog(AIFDesktop.getActiveDesktop().getShell(), "", packCodeDescInfos)).open();
                if(packCodeDescInfos.getGenerateID() != null)
                {
                    itemIDText.setText(packCodeDescInfos.getGenerateID());
                    if(itemNameText != null)
                        itemNameText.setText(packCodeDescInfos.getNameValue());
                    //remove and add 2017-10-12
                    itemIDText.setEnabled(false);
                    assignButton.setEnabled(false);
//                    if(packCodeDescInfos.getCodeRuleName().trim().length() > 0)
//                    {
//                        itemIDText.setEnabled(false);
//                        assignButton.setEnabled(false);
//                        setCodeInfo(composite.getParent().getParent().getParent(), packCodeDescInfos, null);
//                    }
                    //end
                }
            }
            catch(TCException e)
            {
                e.printStackTrace();
            }
        }

        private TCPropertyDescriptor m_propDesc;
        private SWTComboBox m_comboBox;
        private Button m_sourceObject;

        public IC_GenerateIDButtonSelectionAdapter(TCPropertyDescriptor tcpropertydescriptor, SWTComboBox swtcombobox)
        {
            super();
            m_propDesc = tcpropertydescriptor;
            m_comboBox = swtcombobox;
        }
    }


    public CUSTAutoAssignItemIDPropertyBean(FormToolkit formtoolkit, Composite composite, boolean flag, Map map)
    {
        item_id = "object_name";
        object_name = "object_name";
        object_desc = "object_desc";
        revision_id1 = "item_revision_id";
        revision_id2 = "revision:item_revision_id";
        textObject_name = "object_name";
        textObject_desc = "object_desc";
        textObject_rev1 = "item_revision_id";
        textObject_rev2 = "revision:item_revision_id";
        assignButton = null;
        m_localComposite = new Composite(composite, 0);
        addDefaultBeanControl(formtoolkit, m_localComposite, flag, map);
    }

    protected void addDefaultBeanControl(FormToolkit formtoolkit, Composite composite, boolean flag, Map map)
    {
        m_propBean = new TextfieldPropertyBean(formtoolkit, composite, flag, map);
        setPageAttrib(map);
        setControl(m_propBean.getControl());
        m_propBean.addPropertyChangeListener(this);
        ((TextfieldPropertyBean)m_propBean).removePropertyChangeListner();
        ((TextfieldPropertyBean)m_propBean).getTextControl().addPropertyChangeListener(this);
    }

    private void setPageAttrib(Map map)
    {
        String s = map == null ? null : (String)map.get("column");
        int i = 32;
        if(s != null && s.length() > 0)
            try
            {
                i = Integer.parseInt(s);
            }
            catch(NumberFormatException numberformatexception)
            {
                Logger.getLogger(com.teamcenter.rac.viewer.stylesheet.beans.AbstractAutoAssignBean.class).error(numberformatexception.getClass().getName(), numberformatexception);
            }
        setSize(i);
    }

    private void setSize(int i)
    {
        if(m_propBean instanceof TextfieldPropertyBean)
        {
            int j = i;
            if(j == 0)
                j = 32;
            int k = j * 5;
            GridData griddata = new GridData(4, 16777216, true, true);
            griddata.widthHint = k;
            ((TextfieldPropertyBean)m_propBean).setLayoutData(griddata);
        }
    }

    public boolean isPropertyModified(TCProperty tcproperty)
        throws Exception
    {
        return m_propBean.isPropertyModified(tcproperty);
    }

    public void setModifiable(boolean flag)
    {
        m_propBean.setModifiable(flag);
    }

    public boolean isMandatory()
    {
        return m_propBean.isMandatory();
    }

    public Object getEditableValue()
    {
        return m_propBean.getEditableValue();
    }

    public void load(TCProperty tcproperty)
        throws Exception
    {
        load(tcproperty.getPropertyDescriptor());
        setDirty(false);
    }

    public void load(TCPropertyDescriptor tcpropertydescriptor)
        throws Exception
    {
        setLayout(2);
        m_propBean.setProperty(getProperty());
        descriptor = tcpropertydescriptor;
        NamingRule namingrule = descriptor.getNamingRule();
        if(namingrule != null)
        {
            String as[] = getNamingRulePatternsWithCounters(tcpropertydescriptor);
            String s = getPreferredNamingRulePattern(tcpropertydescriptor);
            if(as != null && as.length > 0)
            {
                m_validationNeeded = true;
                addMoreWidgets(tcpropertydescriptor, as, s);
            } else
            {
                setLayout(1);
                m_validationNeeded = true;
            }
        } else
        {
            setLayout(2);
            Button button = getButtonWidget();
            button.setData("RCAF_ID", tcpropertydescriptor.getName());
            assignButton = button;
            button.addSelectionListener(new IC_GenerateIDButtonSelectionAdapter(tcpropertydescriptor, null));
        }
        m_propBean.load(tcpropertydescriptor);
    }

    private void addMoreWidgets(TCPropertyDescriptor tcpropertydescriptor, String as[], String s)
    {
        setLayout(3);
        SWTComboBox swtcombobox = new SWTComboBox(m_localComposite, 2056);
        GridData griddata = new GridData(4, 16777216, true, true);
        swtcombobox.setLayoutData(griddata);
        String as1[];
        int j = (as1 = as).length;
        for(int i = 0; i < j; i++)
        {
            String s1 = as1[i];
            swtcombobox.addItem(s1);
        }

        swtcombobox.setAutoCompleteSuggestive(false);
        if(s != null && s.length() > 0)
            swtcombobox.setSelectedItem(s);
        else
            swtcombobox.setSelectedIndex(0);
        Button button = getButtonWidget();
        button.setData("RCAF_ID", tcpropertydescriptor.getName());
        button.addSelectionListener(new IC_GenerateIDButtonSelectionAdapter(tcpropertydescriptor, swtcombobox));
    }

    private String[] getNamingRulePatternsWithCounters(TCPropertyDescriptor tcpropertydescriptor)
    {
        DataManagementService datamanagementservice = DataManagementService.getService(getSession());
        com.teamcenter.services.rac.core._2008_06.DataManagement.GetNRPatternsWithCountersResponse getnrpatternswithcountersresponse = null;
        com.teamcenter.services.rac.core._2008_06.DataManagement.NRAttachInfo anrattachinfo[] = new com.teamcenter.services.rac.core._2008_06.DataManagement.NRAttachInfo[1];
        anrattachinfo[0] = new com.teamcenter.services.rac.core._2008_06.DataManagement.NRAttachInfo();
        anrattachinfo[0].propName = getProperty();
        anrattachinfo[0].typeName = getOwningTypeName(tcpropertydescriptor);
        getnrpatternswithcountersresponse = datamanagementservice.getNRPatternsWithCounters(anrattachinfo);
        com.teamcenter.services.rac.core._2008_06.DataManagement.PatternsWithCounters apatternswithcounters[] = getnrpatternswithcountersresponse.patterns;
        return apatternswithcounters[0].patternStrings;
    }

    protected String getOwningTypeName(TCPropertyDescriptor tcpropertydescriptor)
    {
        String s = tcpropertydescriptor.getTypeComponent().getOwningType();
        if(s == null || s.isEmpty())
            s = tcpropertydescriptor.getTypeComponent().getTypeName();
        return s;
    }

    private String getPreferredNamingRulePattern(TCPropertyDescriptor tcpropertydescriptor)
    {
        String s = tcpropertydescriptor.getTypeComponent().getOwningType().toString();
        String s1 = s == null || s.isEmpty() ? tcpropertydescriptor.getTypeComponent().toString() : s;
        String as[] = {
            tcpropertydescriptor.getName()
        };
        String as1[] = {
            s1
        };
        com.teamcenter.rac.commands.newitem.NamingRule anamingrule[] = NamingRulesHelper.getInstance().getNamingRules(getSession(), as1, as);
        return anamingrule[0].getPreferredPattern();
    }

    private Button getButtonWidget()
    {
        Button button = new Button(m_localComposite, 0);
        button.setText(appReg.getString("assignButton.TEXT"));
        return button;
    }

    public TCSession getSession()
    {
        TCSession tcsession = null;
        try
        {
            tcsession = (TCSession)Activator.getDefault().getSessionService().getSession("com.teamcenter.rac.kernel.TCSession");
        }
        catch(Exception exception)
        {
            Logger.getLogger(com.teamcenter.rac.viewer.stylesheet.beans.AbstractAutoAssignBean.class).error(exception);
            return null;
        }
        return tcsession;
    }

    protected void setLayout(int i)
    {
        if(m_localComposite != null)
        {
            GridLayout gridlayout = new GridLayout(i, false);
            gridlayout.marginHeight = 0;
            gridlayout.marginWidth = 0;
            m_localComposite.setLayout(gridlayout);
            GridData griddata = new GridData(4, 16777216, true, true);
            m_localComposite.setLayoutData(griddata);
        }
    }

    public TCProperty getPropertyToSave(TCProperty tcproperty)
        throws Exception
    {
        return tcproperty;
    }

    public void setUIFValue(Object obj)
    {
        m_propBean.setUIFValue(obj);
    }

    public void setCodeInfo(Composite composite, PackCodeDescInfos packCodeDescInfos, Control next)
    {
        try
        {
            Control childrens[] = composite.getChildren();
            for(int i = 0; i < childrens.length; i++)
            {
                Control child = childrens[i];
                if(child instanceof Label)
                {
                    Label label = (Label)child;
                    String text = label.getText();
                    if(text.equals("cd9_codeDesc:") || text.equals((new StringBuilder(String.valueOf(getSession().getTextService().getTextValue("cd9_codeDesc")))).append(":").toString()))
                    {
                        if(next instanceof Text)
                        {
                            Text textField = (Text)next;
                            textField.setText(packCodeDescInfos.getIdDesc());
                            textField.setEnabled(false);
                        }
                    } else
                    if(text.equals("cd9_codePattern:") || text.equals((new StringBuilder(String.valueOf(getSession().getTextService().getTextValue("cd9_codePattern")))).append(":").toString()))
                    {
                        if(next instanceof Text)
                        {
                            Text textField = (Text)next;
                            textField.setText(packCodeDescInfos.getCodetz());
                            textField.setEnabled(false);
                        }
                    } else
                    if(text.equals("cd9_codeRuleName:") || text.equals((new StringBuilder(String.valueOf(getSession().getTextService().getTextValue("cd9_codeRuleName")))).append(":").toString()))
                    {
                        if(next instanceof Text)
                        {
                            Text textField = (Text)next;
                            //remove 2017-10-12
//                            textField.setText(packCodeDescInfos.getCodeRuleName());
                            //end
                            textField.setEnabled(false);
                        }
                    } else
                    if(text.equals("cd9_codeID:") || text.equals((new StringBuilder(String.valueOf(getSession().getTextService().getTextValue("cd9_codeID")))).append(":").toString()))
                    {
                        if(next instanceof Text)
                        {
                            Text textField = (Text)next;
                            textField.setText(packCodeDescInfos.getIdjl());
                            textField.setEnabled(false);
                        }
                    } else
                    if(text.equals("cd9_generateID:") || text.equals((new StringBuilder(String.valueOf(getSession().getTextService().getTextValue("cd9_generateID")))).append(":").toString()))
                    {
                        if(next instanceof Text)
                        {
                            Text textField = (Text)next;
                            textField.setText(packCodeDescInfos.getGenerateID());
                            textField.setEnabled(false);
                        }
                    } else
                    if((text.equals("cd9_codeStyle:") || text.equals((new StringBuilder(String.valueOf(getSession().getTextService().getTextValue("cd9_codeStyle")))).append(":").toString())) && (next instanceof Text))
                    {
                        Text textField = (Text)next;
                        textField.setText(packCodeDescInfos.getCodeStyle());
                        textField.setEnabled(false);
                    }
                }
            }

            for(int i = 0; i < childrens.length; i++)
            {
                Control child = childrens[i];
                Control child2 = null;
                if(i + 1 < childrens.length)
                    child2 = childrens[i + 1];
                if(child instanceof Composite)
                    setCodeInfo((Composite)child, packCodeDescInfos, child2);
            }

        }
        catch(TCException e)
        {
            e.printStackTrace();
        }
    }

    public void getNameTextByLabel(Composite composite, String labelName)
    {
        boolean isEqual = false;
        int equalNum = 0;
        Control childrens[] = composite.getChildren();
        for(int i = 0; i < childrens.length; i++)
        {
            Control child = childrens[i];
            if((child instanceof Composite) && !isEqual && isValidLabelByText((Composite)child, labelName))
            {
                isEqual = true;
                equalNum = i;
            }
            if(isEqual)
                if(labelName.equals(object_name) || labelName.equals(textObject_name))
                {
                    if((child instanceof Text) && i == equalNum + 1)
                    {
                        Text textField = (Text)child;
                        itemNameText = textField;
                        return;
                    }
                } else
                if(labelName.equals(object_desc) || labelName.equals(textObject_desc))
                {
                    if((child instanceof Text) && i == equalNum + 1)
                    {
                        Text textField = (Text)child;
                        itemDescText = textField;
                        return;
                    }
                } else
                if((labelName.equals(revision_id1) || labelName.equals(textObject_rev1) || labelName.equals(revision_id2) || labelName.equals(textObject_rev2)) && (child instanceof Text) && i == equalNum + 1)
                {
                    Text textField = (Text)child;
                    itemRevText = textField;
                    return;
                }
        }

    }

    private boolean isValidLabelByText(Composite composite, String labelName)
    {
        boolean isValid = false;
        Control childrens[] = composite.getChildren();
        for(int i = 0; i < childrens.length; i++)
        {
            Control child = childrens[i];
            if(child instanceof Label)
            {
                Label label = (Label)child;
                String text = label.getText();
                if(text.equals((new StringBuilder(String.valueOf(labelName))).append(":").toString()))
                    isValid = true;
            }
        }

        return isValid;
    }

    Text itemIDText;
    Text itemNameText;
    Text itemDescText;
    Text itemRevText;
    String item_id;
    String object_name;
    String object_desc;
    String revision_id1;
    String revision_id2;
    String textObject_name;
    String textObject_desc;
    String textObject_rev1;
    String textObject_rev2;
    public Button assignButton;
    protected AbstractPropertyBean m_propBean;
    private Composite m_localComposite;
    protected static final Registry appReg = Registry.getRegistry(com.teamcenter.rac.viewer.stylesheet.beans.CUSTAutoAssignItemIDPropertyBean.class);
    protected boolean m_validationNeeded;

}