<template>
  <v-card class="mx-auto" tile>
    <v-toolbar color="error" dark flat>
      <v-toolbar-title>Components</v-toolbar-title>
      <v-spacer></v-spacer>
      <v-btn depressed color="white" light :to="localePath('/manager/components/create')" text>
        <v-icon small>icon-add</v-icon>
      </v-btn>
    </v-toolbar>

    <v-card-text>
      <v-list>
        <v-list-item-group
          v-model="selected"
          multiple
          active-class="pink--text"
          @change="syncComponents"
        >
          <template v-for="(item, index) in components">
            <v-list-item :key="item.name" :value="item.id">
              <template v-slot:default="{ active, toggle }">
                <v-list-item-content>
                  <v-list-item-title v-text="item.name"></v-list-item-title>
                </v-list-item-content>

                <v-list-item-action>
                  <v-switch :value="isAdded(item.id)" :disabled="loading" />
                </v-list-item-action>
              </template>
            </v-list-item>

            <v-divider v-if="index + 1 < components.length" :key="index"></v-divider>
          </template>
        </v-list-item-group>
      </v-list>
    </v-card-text>
  </v-card>
</template>


<script>
export default {
  props: {
    model_id: {
      type: Number
    },
    model: {
      type: String
    },
    componentsAttachedIds: {
      type: Array
    }
  },
  data() {
    return {
      components: [],
      selected: [],
      loading: true
    }
  },
  watch: {
    componentsAttachedIds() {
      this.copyComponentsIds()
    }
  },
  async mounted() {
    await this.getComponents()
    this.copyComponentsIds()
  },
  methods: {
    copyComponentsIds() {
      this.selected = [...this.componentsAttachedIds]
    },

    isAdded(componentId) {
      return this.componentsAttachedIds.includes(componentId)
    },

    async getComponents() {
      try {
        this.loading = true
        const response = await this.$axios.get(`/components`)
        this.components = response.data
        this.loading = false
      } catch (error) {
        console.log('TCL: getComponents -> error', error)
      }
    },

    async syncComponents() {
      this.loading = true
      const data = {
        model: this.model,
        model_id: this.model_id,
        components_ids: this.selected
      }

      try {
        const response = await this.$axios.post('/components/sync', data)
        this.$emit('reload-resource')
        this.loading = false
      } catch (error) {
        console.log('TCL: syncComponents -> error', error)
      }
    }
  }
}
</script>