import constants from "./constants";

export default (dc, label, type) => {
  const defaultType = dc.getType("default");
  const defaultModel = defaultType.model;
  const defaultView = defaultType.view;

  const {
    attrAccordions,
    attrAccordionContainer,
    classAccordionContainer,
    attrAccordionContent,
    selectorAccordion,
    accordionContainerProps,
  } = constants;

  const attrKey = attrAccordionContainer;
  const classKey = classAccordionContainer;

  dc.addType(type, {
    model: defaultModel.extend(
      {
        defaults: {
          ...defaultModel.prototype.defaults,
          name: label,
          draggable: `[${attrAccordions}, ${attrAccordionContent}]`,
          droppable: false,
          copyable: true,
          removable: true,
          ...accordionContainerProps,
        },

        init() {
          const attrs = this.getAttributes();
          attrs[attrKey] = 1;
          this.setAttributes(attrs);
          classKey && this.addClass(classKey);
          this.listenTo(this, "add", this.onAdd);
        },

        onAdd() {
          const componentModels = this.components().models;

          if (componentModels && Array.isArray(componentModels)) {
            let accordionContentID;
            for (let i = componentModels.length - 1; i >= 0; i--) {
              const model = componentModels[i];
              const attrs = model.getAttributes();
              if (attrs[`${attrAccordionContent}`]) {
                accordionContentID = model.getId();
                model.setId(accordionContentID);
              } else {
                model.addAttributes({
                  [selectorAccordion]: `#${accordionContentID}`,
                });
              }
            }
          }
        },
      },
      {
        isComponent(el) {
          if (el.hasAttribute && el.hasAttribute(attrKey)) {
            return { type };
          }
        },
      }
    ),

    view: defaultView,
  });
};
