/**
   * Loads the ASI template to be used.
   *
   * @param fromAttributeSetInstanceId
   * @return
   *     <ul>
   *       <li>ASI template
   *       <li><code>null</code> if this is not a valid settings and we need to dispose the dialog
   *     </ul>
   *
   * @throws AdempiereException if something failed
   */
  private final MAttributeSetInstance loadASITemplate(final int fromAttributeSetInstanceId) {
    final Properties ctx = getCtx();
    final int productId = getM_Product_ID();
    final boolean isPureProductASI = isPureProductASI();

    //
    // If there is not product specified
    // and we need a pure product ASI (i.e. not the ASI that we configure on product level)
    // => this dialog does not make sense and we need to dispose it ASAP
    // TODO: in future we shall do this checking BEFORE we reach this point
    if (productId <= 0 && isPureProductASI) {
      return null;
    }

    final MAttributeSetInstance asiTemplate;

    //
    // Load/Create the ASI
    // Get the M_AttributeSet.
    MAttributeSet as = null;
    if (productId > 0) {
      // Get/Create the ASI
      asiTemplate = MAttributeSetInstance.get(ctx, fromAttributeSetInstanceId, productId);
      if (asiTemplate == null) {
        throw new AdempiereException(
            "@NotFound@ @M_AttributeSetInstance_ID@ (@M_Product_ID@=" + productId + ")");
      }
      Env.setContext(ctx, m_WindowNo, "M_AttributeSet_ID", asiTemplate.getM_AttributeSet_ID());

      // Get Attribute Set
      as = asiTemplate.getMAttributeSet();
    } else {
      final int M_AttributeSet_ID = attributeContext.getM_AttributeSet_ID();
      asiTemplate =
          new MAttributeSetInstance(ctx, 0, M_AttributeSet_ID, ITrx.TRXNAME_None); // new ASI
      as = asiTemplate.getMAttributeSet();
      if (as == null && M_AttributeSet_ID == 0) {
        // FIXME: workaround to deal with M_AttributeSet_ID=0 which is an existing record
        as =
            queryBL
                .createQueryBuilder(I_M_AttributeSet.class)
                .setContext(ctx, ITrx.TRXNAME_None)
                .addEqualsFilter(I_M_AttributeSet.COLUMNNAME_M_AttributeSet_ID, 0)
                .create()
                .firstOnlyNotNull(MAttributeSet.class);
        asiTemplate.setMAttributeSet(as);
      }
    }
    // Product has no Attribute Set
    if (as == null) {
      throw new AdempiereException("@PAttributeNoAttributeSet@");
    }
    // Product has no Instance Attributes
    if (isPureProductASI && !as.isInstanceAttribute()) {
      throw new AdempiereException("@PAttributeNoInstanceAttribute@");
    }

    return asiTemplate;
  }
  public static MAttributeSet createAttributeSet(Properties ctx, String name)
      throws OperationException {
    MAttributeSet attributeSet = new MAttributeSet(ctx, 0, null);
    attributeSet.setMandatoryType(MAttributeSet.MANDATORYTYPE_NotMandatary);
    attributeSet.setIsSerNo(false);
    attributeSet.setIsSerNoMandatory(false);
    attributeSet.setIsInstanceAttribute(false);
    attributeSet.setName(name);

    PoManager.save(attributeSet);

    return attributeSet;
  }
  private MAttributeSetInstance saveSelection0() {
    log.info("");

    final MAttributeSet as = asiTemplate.getMAttributeSet();
    Check.assumeNotNull(as, "as not null");

    // Create a new ASI which is copying the existing one
    final MAttributeSetInstance asi =
        new MAttributeSetInstance(getCtx(), 0, ITrx.TRXNAME_ThreadInherited);
    InterfaceWrapperHelper.copyValues(
        asiTemplate, asi, false); // honorIsCalculated=false => copy everything
    asi.setM_AttributeSet(as); // make sure we have the right AttributeSet model set

    //
    boolean changed = false;
    final Set<String> mandatory = new LinkedHashSet<>();

    // Lot
    if (!m_productWindow && as.isLot()) {
      String text = fieldLotString.getText();
      asi.setLot(text);
      if (as.isLotMandatory() && (text == null || text.length() == 0)) {
        mandatory.add(msgBL.translate(getCtx(), "Lot"));
      }
      changed = true;
    } // Lot

    // Serial No
    if (!m_productWindow && as.isSerNo()) {
      final String serNo = fieldSerNo.getText();
      asi.setSerNo(serNo);
      if (as.isSerNoMandatory() && Check.isEmpty(serNo, true)) {
        mandatory.add(msgBL.translate(getCtx(), "SerNo"));
      }
      changed = true;
    } // SerNo

    //
    // Guarantee Date (if required)
    if (fieldGuaranteeDateDisplayed) {
      final Timestamp guaranteeDate = fieldGuaranteeDate.getValue();
      asi.setGuaranteeDate(guaranteeDate);
      if (as.isGuaranteeDate() && as.isGuaranteeDateMandatory() && guaranteeDate == null) {
        mandatory.add(msgBL.translate(getCtx(), I_M_AttributeSetInstance.COLUMNNAME_GuaranteeDate));
      }
      changed = true;
    }

    //
    // New Instance
    if (changed || asi.getM_AttributeSetInstance_ID() <= 0) {
      InterfaceWrapperHelper.save(asi);
      changed = true;
    }
    final int attributeSetInstanceId = asi.getM_AttributeSetInstance_ID();

    //
    // Save Instance Attributes
    for (final MAttribute attribute : m_attributes) {
      final CEditor editor = attributeId2editor.get(attribute.getM_Attribute_ID());

      if (MAttribute.ATTRIBUTEVALUETYPE_List.equals(attribute.getAttributeValueType())) {
        @SuppressWarnings("unchecked")
        final CComboBox<I_M_AttributeValue> editorCombo = (CComboBox<I_M_AttributeValue>) editor;
        final I_M_AttributeValue attributeValue = editorCombo.getSelectedItem();
        if (attribute.isMandatory() && attributeValue == null) {
          mandatory.add(attribute.getName());
        }
        attribute.setMAttributeInstance(attributeSetInstanceId, attributeValue);
      } else if (MAttribute.ATTRIBUTEVALUETYPE_Number.equals(attribute.getAttributeValueType())) {
        final VNumber editorNumber = (VNumber) editor;
        final BigDecimal value = (BigDecimal) editorNumber.getValue();
        if (attribute.isMandatory() && value == null) {
          mandatory.add(attribute.getName());
        }
        attribute.setMAttributeInstance(attributeSetInstanceId, value);
      } else if (MAttribute.ATTRIBUTEVALUETYPE_Date.equals(attribute.getAttributeValueType())) {
        final VDate editorDate = (VDate) editor;
        final Timestamp value = editorDate.getValue();
        if (attribute.isMandatory() && value == null) {
          mandatory.add(attribute.getName());
        }
        attribute.setMAttributeInstance(attributeSetInstanceId, value);
      } else {
        final VString editorString = (VString) editor;
        final String value = editorString.getText();
        if (attribute.isMandatory() && Check.isEmpty(value, false)) {
          mandatory.add(attribute.getName());
        }
        attribute.setMAttributeInstance(attributeSetInstanceId, value);
      }
      changed = true;
    } // for all attributes

    //
    // Throw exception if there are some mandatory fields which were not set
    if (!mandatory.isEmpty()) {
      throw new AdempiereException("@FillMandatory@ " + StringUtils.toString(mandatory, ", "));
    }

    // Save Model
    if (changed) {
      asi.setMAttributeSet(as); // NOTE: this is workaround for the case when M_AttributeSet_ID=0
      attributeSetInstanceBL.setDescription(asi);
      InterfaceWrapperHelper.save(asi);
    }

    return asi;
  }
  /** Initialize all panel fields and editors based on {@link #asiTemplate}. */
  private final void initAttributes() {
    final Properties ctx = getCtx();
    final boolean isProductWindow = isProductWindow();
    final boolean isProcessParameter = isProcessParameter();
    final boolean isPureProductASI = isPureProductASI();
    final boolean allowSelectExistingASI = isAllowSelectExistingASI();
    final MAttributeSet as = asiTemplate.getMAttributeSet();
    Check.assumeNotNull(as, "attribute set not null");
    final boolean isASITemplateNew = asiTemplate.getM_AttributeSetInstance_ID() <= 0;

    //
    // Show Select existing ASI (if allowed)
    if (allowSelectExistingASI) {
      // New/Edit - Selection
      if (isASITemplateNew) // new ASI
      cbNewEdit.setText(msgBL.getMsg(ctx, "NewRecord"));
      else cbNewEdit.setText(msgBL.getMsg(ctx, "EditRecord"));
      cbNewEdit.addActionListener(this);
      centerPanel.add(cbNewEdit, new ALayoutConstraint(m_row++, 0));
      bSelectExistingASI.setText(msgBL.getMsg(ctx, "SelectExisting"));
      bSelectExistingASI.addActionListener(this);
      centerPanel.add(bSelectExistingASI, null);
    }

    //
    // Fetch M_Attributes
    final List<MAttribute> attributes;
    if (isProductWindow) {
      attributes = Arrays.asList(as.getMAttributes(false)); // non-instance attributes
    } else if (isPureProductASI) {
      // Regular product's attribute set instance attributes
      attributes = Arrays.asList(as.getMAttributes(true)); // all instance attributes
    } else if (isProcessParameter) {
      final IQueryBuilder<MAttribute> attributesQueryBuilder =
          queryBL
              .createQueryBuilder(MAttribute.class)
              .setContext(ctx, ITrx.TRXNAME_None)
              .addOnlyActiveRecordsFilter()
              .addOnlyContextClient();
      attributesQueryBuilder
          .orderBy()
          .addColumn(I_M_Attribute.COLUMNNAME_Name)
          .addColumn(I_M_Attribute.COLUMNNAME_M_Attribute_ID);
      attributes = attributesQueryBuilder.create().list(MAttribute.class);
    } else {
      attributes = Collections.emptyList();
    }

    //
    // Create attributes UI editors
    for (final MAttribute attribute : attributes) {
      if (!attributeExcludeBL.isExcludedAttribute(
          attribute, as, m_AD_Column_ID, attributeContext.isSOTrx())) {
        addAttributeLine(attribute);
      }
    }

    //
    // Lot
    if (isPureProductASI && as.isLot()) {
      CLabel label = new CLabel(msgBL.translate(ctx, "Lot"));
      label.setLabelFor(fieldLotString);
      centerPanel.add(label, new ALayoutConstraint(m_row++, 0));
      centerPanel.add(fieldLotString, null);
      fieldLotString.setText(asiTemplate.getLot());
      // M_Lot_ID
      // int AD_Column_ID = 9771; // M_AttributeSetInstance.M_Lot_ID
      // fieldLot = new VLookup ("M_Lot_ID", false,false, true,
      // MLookupFactory.get(getCtx(), m_WindowNo, 0, AD_Column_ID, DisplayType.TableDir));
      final String sql =
          "SELECT M_Lot_ID, Name "
              + "FROM M_Lot l "
              + "WHERE EXISTS (SELECT M_Product_ID FROM M_Product p "
              + "WHERE p.M_AttributeSet_ID="
              + asiTemplate.getM_AttributeSet_ID()
              + " AND p.M_Product_ID=l.M_Product_ID)";
      fieldLot = new CComboBox<>(DB.getKeyNamePairs(sql, true));
      label = new CLabel(msgBL.translate(ctx, "M_Lot_ID"));
      label.setLabelFor(fieldLot);
      centerPanel.add(label, new ALayoutConstraint(m_row++, 0));
      centerPanel.add(fieldLot, null);
      if (asiTemplate.getM_Lot_ID() > 0) {
        for (int i = 1; i < fieldLot.getItemCount(); i++) {
          KeyNamePair pp = fieldLot.getItemAt(i);
          if (pp.getKey() == asiTemplate.getM_Lot_ID()) {
            fieldLot.setSelectedIndex(i);
            fieldLotString.setEditable(false);
            break;
          }
        }
      }
      fieldLot.addActionListener(this);
      // New Lot Button
      if (asiTemplate.getMAttributeSet().getM_LotCtl_ID() > 0) {
        if (Env.getUserRolePermissions().isTableAccess(MLot.Table_ID, false)
            && Env.getUserRolePermissions().isTableAccess(MLotCtl.Table_ID, false)
            && !asiTemplate.isExcludeLot(m_AD_Column_ID, attributeContext.isSOTrx())) {
          centerPanel.add(bLot, null);
          bLot.addActionListener(this);
        }
      }
      // Popup
      fieldLot.addMouseListener(new VPAttributeDialog_mouseAdapter(this)); // popup
      mZoom = new CMenuItem(msgBL.getMsg(ctx, "Zoom"), Images.getImageIcon2("Zoom16"));
      mZoom.addActionListener(this);
      popupMenu.add(mZoom);
    } // Lot

    //
    // SerNo
    if (isPureProductASI && as.isSerNo()) {
      CLabel label = new CLabel(msgBL.translate(ctx, "SerNo"));
      label.setLabelFor(fieldSerNo);
      fieldSerNo.setText(asiTemplate.getSerNo());
      centerPanel.add(label, new ALayoutConstraint(m_row++, 0));
      centerPanel.add(fieldSerNo, null);
      // New SerNo Button
      if (asiTemplate.getMAttributeSet().getM_SerNoCtl_ID() != 0) {
        if (Env.getUserRolePermissions().isTableAccess(MSerNoCtl.Table_ID, false)
            && !asiTemplate.isExcludeSerNo(m_AD_Column_ID, attributeContext.isSOTrx())) {
          centerPanel.add(bSerNo, null);
          bSerNo.addActionListener(this);
        }
      }
    } // SerNo

    //
    // GuaranteeDate.
    // We are displaying it if we deal with a pure product ASI (i.e. user is not editing the ASI
    // from product window),
    // and if:
    // * the attribute set requires a GuaranteeDate
    // * or if the ASI has a GuaranteeDate already set
    if (isPureProductASI && (as.isGuaranteeDate() || asiTemplate.getGuaranteeDate() != null)) {
      CLabel label = new CLabel(msgBL.translate(ctx, "GuaranteeDate"));
      label.setLabelFor(fieldGuaranteeDate);
      if (isASITemplateNew) {
        Date guaranteeDate = asiTemplate.getGuaranteeDate();
        if (guaranteeDate == null) {
          guaranteeDate =
              attributesBL.calculateBestBeforeDate(
                  ctx,
                  m_M_Product_ID, // product
                  attributeContext.getC_BPartner_ID(), // vendor bpartner
                  Env.getDate(ctx) // dateReceipt
                  );
        }
        fieldGuaranteeDate.setValue(guaranteeDate);
      } else {
        fieldGuaranteeDate.setValue(asiTemplate.getGuaranteeDate());
      }
      centerPanel.add(label, new ALayoutConstraint(m_row++, 0));
      centerPanel.add(fieldGuaranteeDate, null);
      fieldGuaranteeDateDisplayed = true;
    } // GuaranteeDate

    // Make sure we have at least something to edit or something to select,
    // else there is no point in showing empty this window.
    if (m_row == 0) {
      throw new AdempiereException("@PAttributeNoInfo@");
    }

    //
    // New/Edit Window
    if (allowSelectExistingASI) {
      cbNewEdit.setSelected(isASITemplateNew);
      cmd_newEdit();
    }

    //
    // Attrribute Set Instance Description
    {
      final CLabel labelDescription = new CLabel(msgBL.translate(ctx, "Description"));
      labelDescription.setLabelFor(fieldDescription);
      fieldDescription.setText(asiTemplate.getDescription());
      fieldDescription.setEditable(false);
      centerPanel.add(labelDescription, new ALayoutConstraint(m_row++, 0));
      centerPanel.add(fieldDescription, null);
    }

    // Window usually to wide (??)
    {
      final Dimension dd = centerPanel.getPreferredSize();
      dd.width = Math.min(500, dd.width);
      centerPanel.setPreferredSize(dd);
    }
  } // initAttribute