<template>
  <div class="space-folder-form-container">
    <global-form
      form-id="manage-space-folder-form"
      :endpoint="endpoint"
      :http-verb="isEdition ? 'put' : 'post'"
      :steps="['request', 'redirect']"
      @onRedirect="handleRedirection"
    >
      <template #fields>
        <input-text
          model-name="title"
          :rules="['required']"
          :label="$_tr('title')"
          :default-value="defaultValue('title')"
        />

        <!-- AJOUT -->
        <input-text
          v-if="requestDone && !isEdition"
          model-name="franchised_spaces_folders"
          :default-value="currentFolder.title || $_tr('root')"
          :callback="() => currentFolder.uuid || null"
          :label="$_tr('folder')"
          :readonly="true"
        />

        <!-- EDITION -->
        <input-selectbox
          v-else-if="requestDone"
          model-name="franchised_spaces_folders"
          :input-data="folders"
          :default-value="
            getCheckedData(fetchedData, ['folder', 'parentFolder', 'uuid'])
          "
          object-label-key="title"
          object-value-key="uuid"
          :label="$_tr('folder')"
        />

        <input-text
          model-name="franchised_spaces"
          :default-value="fetchedData.space.title"
          :callback="() => fetchedData.space.uuid"
          :readonly="true"
          :label="$_tr('space')"
        />

        <input-hidden
          model-name="bundle"
          default-value="franchised_spaces_folders"
          :rules="['required']"
        />

        <input-hidden
          model-name="type"
          default-value="node"
          :rules="['required']"
        />
      </template>
    </global-form>
  </div>
</template>

<script>
import { http } from '@inside-library/helpers/Http'

import { isEditionRole, isFranchisedUser } from '../../helpers/index'

export default {
  name: 'SpaceFolderForms',
  $_i18nRootPath: 'customs.SPACE.FOLDER_FORM',
  props: {
    fetchedData: {
      type: Object,
      required: true
    }
  },
  data() {
    return {
      isEdition: this.fetchedData.isEdition,
      requestDone: false,
      folderUuid: this.$route.query.folder,
      folders: [],
      currentFolder: {},
      parentFolder: this.getCheckedData(
        this.fetchedData,
        ['folder', 'parentFolder'],
        {}
      )
    }
  },
  computed: {
    endpoint() {
      return this.isEdition
        ? `content/franchised_spaces_folders/${this.fetchedData.folder.uuid}`
        : 'content/franchised_spaces_folders'
    },
    defaultValue() {
      return (name, defaultValue, callback = data => data) =>
        callback(
          this.getCheckedData(this.fetchedData, ['folder', name], defaultValue)
        )
    },
    editionEnabled() {
      return isEditionRole() || isFranchisedUser()
    }
  },
  beforeMount() {
    if (this.fetchedData.error || !this.editionEnabled) {
      this.$router.push({
        name: 'ErrorPage',
        params: {
          code: '403'
        }
      })
    }

    this.fetchFolders()
  },
  methods: {
    async fetchFolders() {
      try {
        const { data } = await http.get('content/franchised_spaces_folders', {
          fields: ['title', 'uuid'],
          filters: {
            franchised_spaces: { 'uuid:eq': this.fetchedData.space.uuid },
            'status:eq': 1
          }
        })

        this.folders = data

        this.requestDone = true
        this.currentFolder =
          data.find(({ uuid }) => uuid === this.$route.query.folder) || {}
      } catch (err) {
        throw new Error(err)
      }
    },
    handleRedirection() {
      this.$router.push({
        name: 'Space',
        params: {
          slug: this.fetchedData.space.slug[0]
        }
      })
    }
  }
}
</script>

<style></style>
