<template>
  <div class="u-pt2">
    <div v-if="matchingPlugins">
      <component
        v-for="plugin of matchingPlugins"
        :is="handlerComponent"
        :key="plugin.id"
        :plugin="plugin"
        :integrations-url="integrationsUrl"
        :context="{ ...context, pluginConfig: plugin.configuration }"
        :plugin-slot-name="pluginSlotName"
        :plugin-slot-handler="handlerComponent"
        :plugin-slot-disabled="pluginSlotDisabled"
        :disabled-message="disabledMessage"
        :plugin-methods="pluginMethods"
        :access-token="accessToken"
        v-on="$listeners"
      />
    </div>
  </div>
</template>

<script>
import { createApiClient } from './api'
import ButtonRow from './ButtonRow.vue'
import AutoComplete from './AutoComplete.vue'
import Markup from './Markup.vue'
import AutoRun from './AutoRun'

export default {
  name: 'PluginSlot',
  components: {
    'bc-plugin-button-row': ButtonRow,
    'bc-plugin-auto-complete': AutoComplete,
    'bc-plugin-markup': Markup,
    'bc-plugin-auto-run': AutoRun
  },
  props: {
    pluginSlotName: {
      type: String,
      required: true
    },
    pluginsUrl: {
      type: String,
      required: true
    },
    integrationsUrl: {
      type: String,
      required: true
    },
    accessToken: {
      type: String
    },
    handlerComponent: {
      type: String,
      required: true
    },
    context: {
      type: Object,
      default: () => ({})
    },
    pluginSlotDisabled: {
      type: Boolean,
      default: false
    },
    disabledMessage: {
      type: String,
      default: ''
    },
    pluginMethods: {
      type: Object,
      default: () => ({})
    }
  },
  data () {
    return {
      plugins: []
    }
  },
  computed: {
    matchingPlugins () {
      return this.plugins.filter(plugin => {
        return plugin.plugin_slots.some(slot => {
          return slot.slot_name === this.pluginSlotName
        })
      })
    }
  },
  async mounted () {
    await this.loadPlugins()
  },
  methods: {
    async loadPlugins () {
      const pluginsApi = createApiClient(this.pluginsUrl, this.accessToken)
      const response = await pluginsApi.findAll()
      this.plugins = response.data
    }
  }
}
</script>
