import { is } from 'bpmn-js/lib/util/ModelUtil.js'
import FunctionSelect from '@/bpmn/modules/service-desk/PropertiesProvider/FunctionSelect.js'
import { ensureExtensionProperty } from '@/bpmn/utils/extesion-properties.js'

export default function PropertiesProvider(propertiesPanel, translate, commandStack, bpmnFactory) {
  this.translate = translate
  this.commandStack = commandStack
  this.bpmnFactory = bpmnFactory

  propertiesPanel.registerProvider(500, this)
}

PropertiesProvider.$inject = [
  'propertiesPanel',
  'translate',
  'commandStack',
  'bpmnFactory',
]

PropertiesProvider.prototype.getGroups = function (element) {
  const { translate, commandStack, bpmnFactory } = this

  return (groups) => {
    if (!is(element, 'bpmn:ScriptTask')) {
      return groups
    }

    return groups.map((group) => {
      if (group.id === 'CamundaPlatform__ExtensionProperties') {
        const propertyName = 'functionName'
        const id = `${element.id}-extensionProperty-${propertyName}`

        const property = ensureExtensionProperty(bpmnFactory, commandStack, element, propertyName)

        const groupItem = group.items.find((item) => {
          return !!item.entries.find(entry => entry.property.name === propertyName)
        })
        const entry = {
          id,
          component: FunctionSelect,
          property,
        }

        if (groupItem) {
          groupItem.id = id
          groupItem.label = translate('Function name')
          groupItem.entries = [entry]
        }
        else {
          group.items.unshift({
            id,
            label: translate('Function name'),
            entries: [
              {
                id,
                component: FunctionSelect,
                property,
              },
            ],
            autoFocusEntry: `${id}-name`,
          })
        }
      }

      return group
    })
  }
}
