/**
   * DOC zli Comment method "guessSchema".
   *
   * @param processDescription
   */
  public void guessSchema(ProcessDescription processDescription) {
    informationLabel.setText(
        "   " + Messages.getString("FileStep3.guessIsDone")); // $NON-NLS-1$ //$NON-NLS-2$
    // clear all items
    tableEditorView.getMetadataEditor().removeAll();
    List<MetadataColumn> columns = new ArrayList<MetadataColumn>();

    List<IMetadataColumn> listColumns = processDescription.getSchema().get(0).getListColumns();
    int size = listColumns.size();
    if (size > 0) {
      for (int i = 0; i < size; i++) {
        MetadataColumn metadataColumn = ConnectionFactory.eINSTANCE.createMetadataColumn();
        metadataColumn.setNullable(listColumns.get(i).isNullable());
        metadataColumn.setLength(listColumns.get(i).getLength());
        metadataColumn.setPattern(listColumns.get(i).getPattern());
        metadataColumn.setTalendType(listColumns.get(i).getTalendType());
        metadataColumn.setPrecision(listColumns.get(i).getPrecision());
        metadataColumn.setLabel(listColumns.get(i).getLabel());
        columns.add(i, metadataColumn);
      }
    }
    tableEditorView.getMetadataEditor().addAll(columns);
    tableEditorView.getTableViewerCreator().layout();
    informationLabel.setText(Messages.getString("FileStep3.guessTip")); // $NON-NLS-1$
  }
  @Override
  protected Control createDialogArea(Composite parent) {
    Composite composite = (Composite) super.createDialogArea(parent);
    composite.setLayout(new FillLayout());

    tableEditor = new MetadataEmfTableEditor("");
    MetadataTable metadataTable = form.getMetadataTable();
    tableEditor.setMetadataTable(metadataTable);
    // tableEditor.removeAll();
    List<MetadataColumn> list = (List<MetadataColumn>) form.getSchemaViewer().getInput();
    tableEditor.addAll(list);

    // if (list.size() > 0) {
    // for (MetadataColumn column : list) {
    // boolean toAdd = true;
    // for (int i = 0; i < currentColumnList.size(); i++) {
    // String label = column.getLabel();
    // String curLabel = currentColumnList.get(i).getLabel();
    // if (label.equals(curLabel)) {
    // toAdd = false;
    // break;
    // }
    // }
    // if (toAdd) {
    // tableEditor.add(column);
    // }
    // }
    // }
    tableEditorView = new MetadataEmfTableEditorView(composite, SWT.NONE);
    tableEditorView.setMetadataEditor(tableEditor);
    addListeners();
    return composite;
  }
  /** Initialize value, forceFocus first field. */
  @Override
  protected void initialize() {
    // init the metadata Table
    String label = MetadataToolHelper.validateValue(metadataTable.getLabel());
    metadataNameText.setText(label);
    metadataCommentText.setText(metadataTable.getComment());
    metadataEditor.setMetadataTable(metadataTable);
    tableEditorView.setMetadataEditor(metadataEditor);
    tableEditorView.getTableViewerCreator().layout();

    if (getConnection().isReadOnly()) {
      adaptFormToReadOnly();
    } else {
      updateStatus(IStatus.OK, null);
    }
  }
  /**
   * Ensures that fields are set. Update checkEnable / use to checkConnection().
   *
   * @return
   */
  @Override
  protected boolean checkFieldsValue() {

    if (metadataNameText.getCharCount() == 0) {
      metadataNameText.forceFocus();
      updateStatus(IStatus.ERROR, Messages.getString("FileStep1.nameAlert")); // $NON-NLS-1$
      return false;
    } else if (!MetadataToolHelper.isValidSchemaName(metadataNameText.getText())) {
      metadataNameText.forceFocus();
      updateStatus(
          IStatus.ERROR, Messages.getString("FileStep1.nameAlertIllegalChar")); // $NON-NLS-1$
      return false;
    } else if (nameExist(metadataNameText.getText())) {
      updateStatus(
          IStatus.ERROR, Messages.getString("CommonWizard.nameAlreadyExist")); // $NON-NLS-1$
      return false;
    }

    if (tableEditorView.getMetadataEditor().getBeanCount() > 0) {
      updateStatus(IStatus.OK, null);
      return true;
    }
    updateStatus(IStatus.ERROR, Messages.getString("FileStep3.itemAlert")); // $NON-NLS-1$

    return false;
  }
  /** DOC ocarbone Comment method "adaptFormToReadOnly". */
  @Override
  protected void adaptFormToReadOnly() {
    readOnly = isReadOnly();
    guessButton.setEnabled(!isReadOnly());
    metadataNameText.setReadOnly(isReadOnly());
    metadataCommentText.setReadOnly(isReadOnly());
    tableEditorView.setReadOnly(isReadOnly());

    // if (getParent().getChildren().length == 1) { // open the table
    // guessButton.setEnabled(false);
    // informationLabel.setVisible(false);
    // }
  }
  /** Main Fields addControls. */
  @Override
  protected void addFieldsListeners() {
    // metadataNameText : Event modifyText
    metadataNameText.addModifyListener(
        new ModifyListener() {

          @Override
          public void modifyText(final ModifyEvent e) {
            MetadataToolHelper.validateSchema(metadataNameText.getText());
            metadataTable.setLabel(metadataNameText.getText());
            checkFieldsValue();
          }
        });
    // metadataNameText : Event KeyListener
    metadataNameText.addKeyListener(
        new KeyAdapter() {

          @Override
          public void keyPressed(KeyEvent e) {
            MetadataToolHelper.checkSchema(getShell(), e);
          }
        });

    // metadataCommentText : Event modifyText
    metadataCommentText.addModifyListener(
        new ModifyListener() {

          @Override
          public void modifyText(final ModifyEvent e) {
            metadataTable.setComment(metadataCommentText.getText());
          }
        });

    // add listener to tableMetadata (listen the event of the toolbars)
    tableEditorView
        .getMetadataEditor()
        .addAfterOperationListListener(
            new IListenableListListener() {

              @Override
              public void handleEvent(ListenableListEvent event) {
                checkFieldsValue();
              }
            });
  }
 /*
  * (non-Javadoc)
  *
  * @see org.eclipse.swt.widgets.Control#setVisible(boolean)
  */
 @Override
 public void setVisible(boolean visible) {
   super.setVisible(visible);
   if (super.isVisible()) {
     initTreeNavigatorNodes();
     changeTableNavigatorStatus(checkFieldsValue());
     SalesforceSchemaConnection originalValueConnection = getOriginalValueConnection();
     if (originalValueConnection.getWebServiceUrl() != null
         && (!originalValueConnection.getWebServiceUrl().equals("")) // $NON-NLS-1$
         && (tableEditorView.getMetadataEditor().getBeanCount() <= 0)) {
       runShadowProcess();
     }
     if (isReadOnly() != readOnly) {
       adaptFormToReadOnly();
     }
   }
   checkFieldsValue();
 }
  /**
   * DOC ocarbone Comment method "refreshMetaData".
   *
   * @param csvArray
   */
  public void refreshMetaDataTable(final CsvArray csvArray, ProcessDescription processDescription) {
    informationLabel.setText(
        "   " + Messages.getString("FileStep3.guessIsDone")); // $NON-NLS-1$ //$NON-NLS-2$

    // clear all items
    tableEditorView.getMetadataEditor().removeAll();

    List<MetadataColumn> columns = new ArrayList<MetadataColumn>();

    if (csvArray == null || csvArray.getRows().isEmpty()) {
      return;
    } else {

      List<String[]> csvRows = csvArray.getRows();
      String[] fields = csvRows.get(0);
      // int numberOfCol = fields.size();

      Integer numberOfCol = getRightFirstRow(csvRows);

      // define the label to the metadata width the content of the first row
      int firstRowToExtractMetadata = 0;

      // the first rows is used to define the label of any metadata
      String[] label = new String[numberOfCol.intValue()];
      for (int i = 0; i < numberOfCol; i++) {
        label[i] = DEFAULT_LABEL + i;
        if (firstRowToExtractMetadata == 0) {
          label[i] =
              "" + processDescription.getSchema().get(0).getListColumns().get(i); // $NON-NLS-1$
        }
      }

      for (int i = 0; i < numberOfCol.intValue(); i++) {
        // define the first currentType and assimile it to globalType
        String globalType = null;
        int lengthValue = 0;
        int precisionValue = 0;

        int current = firstRowToExtractMetadata;
        while (globalType == null) {
          if (LanguageManager.getCurrentLanguage() == ECodeLanguage.JAVA) {
            if (i >= csvRows.get(current).length) {
              globalType = "id_String"; // $NON-NLS-1$
            } else {
              globalType = JavaDataTypeHelper.getTalendTypeOfValue(csvRows.get(current)[i]);
              current++;
              // if (current == csvRows.size()) {
              // globalType = "id_String"; //$NON-NLS-1$
              // }
            }
          } else {
            if (i >= csvRows.get(current).length) {
              globalType = "String"; // $NON-NLS-1$
            } else {
              globalType = PerlDataTypeHelper.getTalendTypeOfValue(csvRows.get(current)[i]);
              current++;
              // if (current == csvRows.size()) {
              // globalType = "String"; //$NON-NLS-1$
              // }
            }
          }
        }

        // for another lines
        for (int f = firstRowToExtractMetadata; f < csvRows.size(); f++) {
          fields = csvRows.get(f);
          if (fields.length > i) {
            String value = fields[i];
            if (!value.equals("")) { // $NON-NLS-1$
              if (LanguageManager.getCurrentLanguage() == ECodeLanguage.JAVA) {
                if (!JavaDataTypeHelper.getTalendTypeOfValue(value).equals(globalType)) {
                  globalType =
                      JavaDataTypeHelper.getCommonType(
                          globalType, JavaDataTypeHelper.getTalendTypeOfValue(value));
                }
              } else {
                if (!PerlDataTypeHelper.getTalendTypeOfValue(value).equals(globalType)) {
                  globalType =
                      PerlDataTypeHelper.getCommonType(
                          globalType, PerlDataTypeHelper.getTalendTypeOfValue(value));
                }
              }
              if (lengthValue < value.length()) {
                lengthValue = value.length();
              }
              int positionDecimal = 0;
              if (value.indexOf(',') > -1) {
                positionDecimal = value.lastIndexOf(',');
                precisionValue = lengthValue - positionDecimal;
              } else if (value.indexOf('.') > -1) {
                positionDecimal = value.lastIndexOf('.');
                precisionValue = lengthValue - positionDecimal;
              }
            } else {
              IPreferenceStore preferenceStore = null;
              if (GlobalServiceRegister.getDefault()
                  .isServiceRegistered(IDesignerCoreUIService.class)) {
                IDesignerCoreUIService designerCoreUiService =
                    (IDesignerCoreUIService)
                        GlobalServiceRegister.getDefault().getService(IDesignerCoreUIService.class);
                preferenceStore = designerCoreUiService.getPreferenceStore();
              }
              if (preferenceStore != null
                  && preferenceStore.getString(MetadataTypeLengthConstants.VALUE_DEFAULT_TYPE)
                      != null
                  && !preferenceStore
                      .getString(MetadataTypeLengthConstants.VALUE_DEFAULT_TYPE)
                      .equals("")) { // $NON-NLS-1$
                globalType =
                    preferenceStore.getString(MetadataTypeLengthConstants.VALUE_DEFAULT_TYPE);
                if (preferenceStore.getString(MetadataTypeLengthConstants.VALUE_DEFAULT_LENGTH)
                        != null
                    && !preferenceStore
                        .getString(MetadataTypeLengthConstants.VALUE_DEFAULT_LENGTH)
                        .equals("")) { // $NON-NLS-1$
                  lengthValue =
                      Integer.parseInt(
                          preferenceStore.getString(
                              MetadataTypeLengthConstants.VALUE_DEFAULT_LENGTH));
                }
              }
            }
          }
        }

        // define the metadataColumn to field i
        MetadataColumn metadataColumn = ConnectionFactory.eINSTANCE.createMetadataColumn();
        // metadataColumn.setPattern("\"dd-MM-yyyy\"");
        // Convert javaType to TalendType
        String talendType = null;
        talendType = globalType;
        if (globalType.equals(JavaTypesManager.FLOAT.getId())
            || globalType.equals(JavaTypesManager.DOUBLE.getId())) {
          metadataColumn.setPrecision(precisionValue);
        } else {
          metadataColumn.setPrecision(0);
        }
        metadataColumn.setTalendType(talendType);
        metadataColumn.setLength(lengthValue);

        // Check the label and add it to the table
        metadataColumn.setLabel(
            tableEditorView.getMetadataEditor().getNextGeneratedColumnName(label[i]));
        columns.add(i, metadataColumn);
      }
    }
    tableEditorView.getMetadataEditor().addAll(columns);
    checkFieldsValue();
    tableEditorView.getTableViewerCreator().layout();
    tableEditorView.getTableViewerCreator().getTable().deselectAll();
    informationLabel.setText(Messages.getString("FileStep3.guessTip")); // $NON-NLS-1$
  }
  public void refreshMetaDataTable(final CsvArray csvArray, ProcessDescription processDescription) {
    informationLabel.setText(
        "   " + Messages.getString("FileStep3.guessIsDone")); // $NON-NLS-1$ //$NON-NLS-2$
    // clear all items
    tableEditorView.getMetadataEditor().removeAll();

    List<MetadataColumn> columns = new ArrayList<MetadataColumn>();
    if (csvArray == null || csvArray.getRows().isEmpty()) {
      return;
    } else {

      List<String[]> csvRows = csvArray.getRows();
      Integer numberOfCol = getRightFirstRow(csvRows);

      // define the label to the metadata width the content of the first row
      int firstRowToExtractMetadata = 0;
      List<IMetadataColumn> listColumns = processDescription.getSchema().get(0).getListColumns();
      // the first rows is used to define the label of any metadata
      String[] label = new String[numberOfCol.intValue()];
      for (int i = 0; i < numberOfCol; i++) {
        label[i] = DEFAULT_LABEL + i;
        if (firstRowToExtractMetadata == 0) {

          label[i] = "" + listColumns.get(i); // $NON-NLS-1$
        }
      }

      for (int i = 0; i < numberOfCol.intValue(); i++) {
        // define the first currentType and assimile it to globalType
        String globalType = null;
        int lengthValue = 0;
        int precisionValue = 0;
        boolean nullAble = true;

        int current = firstRowToExtractMetadata;
        while (globalType == null) {
          String value = csvRows.get(current)[i];
          if (LanguageManager.getCurrentLanguage() == ECodeLanguage.JAVA) {
            if (i >= csvRows.get(current).length) {
              globalType = "id_String"; // $NON-NLS-1$
            } else {
              if (value != null && !"".equals(value)) { // $NON-NLS-1$
                globalType = JavaDataTypeHelper.getTalendTypeOfValue(value);
              } else {
                globalType = listColumns.get(i).getTalendType();
              }
              current++;
            }
          } else {
            if (i >= csvRows.get(current).length) {
              globalType = "String"; // $NON-NLS-1$
            } else {
              globalType = PerlDataTypeHelper.getTalendTypeOfValue(value);
              current++;
            }
          }
        }
        nullAble = listColumns.get(i).isNullable();
        lengthValue = listColumns.get(i).getLength();
        precisionValue = listColumns.get(i).getPrecision();

        // define the metadataColumn to field i
        MetadataColumn metadataColumn = ConnectionFactory.eINSTANCE.createMetadataColumn();
        // Convert javaType to TalendType
        String talendType = null;
        if (LanguageManager.getCurrentLanguage() == ECodeLanguage.JAVA) {
          talendType = globalType;
          if (globalType.equals(JavaTypesManager.FLOAT.getId())
              || globalType.equals(JavaTypesManager.DOUBLE.getId())) {
            metadataColumn.setPrecision(precisionValue);
          } else {
            metadataColumn.setPrecision(0);
          }
        } else {
          talendType =
              PerlTypesManager.getNewTypeName(
                  MetadataTalendType.loadTalendType(
                      globalType, "TALENDDEFAULT", false)); // $NON-NLS-1$
          if (globalType.equals("FLOAT")
              || globalType.equals("DOUBLE")) { // $NON-NLS-1$ //$NON-NLS-2$
            metadataColumn.setPrecision(precisionValue);
          } else {
            metadataColumn.setPrecision(0);
          }
        }

        metadataColumn.setNullable(nullAble);
        metadataColumn.setTalendType(talendType);
        metadataColumn.setLength(lengthValue);
        // bug 6758
        if (talendType.equals("id_Date")) { // $NON-NLS-1$
          String pattern = listColumns.get(i).getPattern();
          metadataColumn.setPattern(pattern);
        }
        // Check the label and add it to the table
        metadataColumn.setLabel(
            tableEditorView.getMetadataEditor().getNextGeneratedColumnName(label[i]));
        columns.add(i, metadataColumn);
      }
    }
    // tableEditorView.getMetadataEditor().registerDataList(columns);
    tableEditorView.getMetadataEditor().addAll(columns);

    checkFieldsValue();
    tableEditorView.getTableViewerCreator().layout();
    informationLabel.setText(Messages.getString("FileStep3.guessTip")); // $NON-NLS-1$
  }
  @Override
  protected void addFieldsListeners() {
    // Navigation : when the user select a table
    tableNavigator.addSelectionListener(
        new SelectionAdapter() {

          @Override
          public void widgetSelected(SelectionEvent e) {
            String schemaLabel = tableNavigator.getSelection()[0].getText();

            // org.talend.core.model.metadata.MetadataTable table = null;
            EList<SalesforceModuleUnit> modules = temConnection.getModules();
            for (int i = 0; i < modules.size(); i++) {
              if (modules.get(i).getModuleName().equals(moduleName)) {
                for (int j = 0; j < modules.get(i).getTables().size(); j++) {
                  if (modules.get(i).getTables().get(j).getLabel().equals(schemaLabel)) {
                    metadataTable = modules.get(i).getTables().get(j);
                    metadataNameText.setText(schemaLabel);
                    break;
                  }
                }
                break;
              }
            }
            metadataEditor.setMetadataTable(metadataTable);
            if (isReadOnly()) {
              addTableButton.setEnabled(false);
            }
            // }
          }
        });
    // metadataNameText : Event modifyText
    metadataNameText.addModifyListener(
        new ModifyListener() {

          @Override
          public void modifyText(final ModifyEvent e) {
            String labelText = metadataNameText.getText();
            MetadataToolHelper.validateSchema(labelText);
            changeTableNavigatorStatus(labelText);
            metadataTable.setLabel(labelText);
            if (tableNavigator.getSelection().length > 0) {
              tableNavigator.getSelection()[0].setText(labelText);
            }
            changeTableNavigatorStatus(checkFieldsValue());

            // kFieldsValue();
          }
        });
    // metadataNameText : Event KeyListener
    metadataNameText.addKeyListener(
        new KeyAdapter() {

          @Override
          public void keyPressed(KeyEvent e) {
            MetadataToolHelper.checkSchema(getShell(), e);
            // initTreeNavigatorNodes();

          }
        });

    // metadataCommentText : Event modifyText
    metadataCommentText.addModifyListener(
        new ModifyListener() {

          @Override
          public void modifyText(final ModifyEvent e) {
            metadataTable.setComment(metadataCommentText.getText());
          }
        });

    // add listener to tableMetadata (listen the event of the toolbars)
    tableEditorView
        .getMetadataEditor()
        .addAfterOperationListListener(
            new IListenableListListener() {

              @Override
              public void handleEvent(ListenableListEvent event) {
                checkFieldsValue();
              }
            });
    // add listener to tableMetadata (listen the event of the toolbars)
    metadataEditor.addAfterOperationListListener(
        new IListenableListListener() {

          @Override
          public void handleEvent(ListenableListEvent event) {
            changeTableNavigatorStatus(checkFieldsValue());
          }
        });
  }