<template>
  <div class="multi-upload-modal-container">
    <div class="modal__header">
      <slot name="closeModal" />
    </div>

    <div class="container">
      <Title>
        {{ $_tr('title') }}
      </Title>

      <global-form :form-id="formId" :use-submit-slot="false">
        <template #fields>
          <input-dropzone
            model-name="documents"
            :form-id="formId"
            :options="{
              uploadMultiple: false,
              chunking: false,
              maxFiles: 10
            }"
            @fileLoaded="onFileAdded"
            @onFileRemoved="onFileRemoved"
            @onDataChange="onDataChange"
          />

          <section v-for="section in sections" :key="section.name">
            <p class="title">{{ section.title }}</p>

            <component
              :is="`input-${field.type}`"
              v-for="field in sectionField(section.name)"
              v-bind="field.data"
              :key="field.name"
              :form-id="formId"
              :model-name="field.modelName"
              :label="field.label"
            >
              <template v-if="field.useUserTemplate" #default="{ node }">
                <user-item-selectbox
                  :username="getCheckedData(node, ['raw', 'label'])"
                  :image="
                    getCheckedData(node, ['raw', 'extraOptions', 'image'])
                  "
                />
              </template>
            </component>
          </section>
        </template>
      </global-form>

      <div class="submit">
        <div>
          <transition name="fadeIn">
            <div v-if="uploading" class="uploading">
              <Loader size="s" box-size="xxs" />

              <p>
                {{
                  $_tc('uploading', [uploadCounter, Object.keys(files).length])
                }}
              </p>
            </div>
          </transition>
        </div>

        <div class="actions">
          <button class="cancel btn-reset">
            {{ $_tr('common.actions.cancel') }}
          </button>

          <button class="post btn" @click="onSubmit">
            {{ $_tr('common.actions.publish') }}
          </button>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { Title, Loader } from 'inside-collection/atoms'
import UserItemSelectbox from '@inside-forms/displays/sub-components/fields-slots/UserItemSelectbox'

import GlobalFormMixin from '@inside-forms/mixins/global-form-mixin'
import GedNavigationMixin from '../mixins/ged-navigation-mixin'

import { http } from '@inside-library/helpers/Http'
import moment from 'moment'

export default {
  name: 'MultiUploadModal',
  $_i18nRootPath: 'customs.MULTI_UPLOAD_MODAL',
  components: {
    Title,
    Loader,
    UserItemSelectbox
  },
  mixins: [GlobalFormMixin, GedNavigationMixin],
  data() {
    return {
      parents: ['folders'],
      contents: ['photo'],
      formId: 'multiple-form-ged',
      files: {},
      currentFolder: this.heritedData.parentFolder,
      uploadCounter: 0,
      uploading: false
    }
  },
  computed: {
    langs() {
      return JSON.parse(process.env.GLOBAL).availableLangs.map(lang => ({
        label: this.$_tr(`fields.langcode.values.${lang}`),
        value: lang
      }))
    },
    sections() {
      return [
        {
          name: 'publications',
          title: this.$_tr('sections.publications')
        },
        {
          name: 'advanced',
          title: this.$_tr('sections.advanced')
        }
      ]
    },
    sectionField() {
      return name => this.fields.filter(field => field.sectionName === name)
    },
    fields() {
      return [
        {
          modelName: 'status',
          sectionName: 'publications',
          type: 'radio',
          label: this.$_tr('fields.status.title'),
          data: {
            'default-value': true,
            inputData: [
              {
                label: this.$_tr('fields.status.values.published'),
                value: true
              },
              {
                label: this.$_tr('fields.status.values.unpublished'),
                value: false
              }
            ]
          }
        },
        {
          modelName: 'langcode',
          sectionName: 'publications',
          type: 'selectbox',
          label: this.$_tr('fields.langcode.title'),
          data: {
            'default-value': this.$_currentLang,
            inputData: this.langs,
            clearable: false
          }
        },
        {
          modelName: 'author',
          sectionName: 'publications',
          type: 'selectbox',
          label: this.$_tr('fields.author.title'),
          useUserTemplate: true,
          data: {
            'default-value': this.getUserInfos.uuid,
            async: {
              contentType: 'users',
              fields: ['uuid', 'lastname', 'firstname', 'image'],
              filters: {
                'is_maintenance:eq': 0,
                'status:eq': 1
              }
            },
            'extra-options-callback': user => ({ image: user.image }),
            'label-callback': user => this.$_username(user),
            'object-value-key': 'uuid',
            clearable: false
          }
        },
        {
          modelName: 'published_at',
          sectionName: 'advanced',
          type: 'date',
          label: this.$_tr('fields.publishedAt.title'),
          data: {
            'day-options': {
              'default-value': new Date(),
              clearButton: false
            },
            'time-options': {
              'default-value': new Date()
            }
          }
        },
        {
          modelName: this.parents[0],
          sectionName: 'advanced',
          type: 'selectbox',
          label: this.$_tr(`fields.${this.parents[0]}.title`),
          data: {
            'default-value': [this.currentFolder],
            async: {
              contentType: this.parents[0],
              fields: ['uuid', 'title'],
              filters: {
                'is_maintenance:eq': 0,
                'status:eq': 1
              }
            },
            'object-label-key': 'title',
            'object-value-key': 'uuid',
            clearable: false,
            callback: data => {
              this.currentFolder = data

              return data
            }
          }
        }
      ]
    }
  },
  watch: {
    async uploadCounter(value) {
      if (value === Object.keys(this.files).length) {
        this.$_triggerToast({
          type: 'success',
          text: this.$_tc('toast.success', value),
          duration: 2000
        })

        this.requestFolder({
          data: {
            slug: this.$store.getters.getCurrentFolder?.slug[0]
          }
        })

        this.closeModal(this.heritedOptions.modalName)
      }
    }
  },
  methods: {
    onDataChange(data) {
      if (data.value) {
        const file = Object.entries(this.files).find(item =>
          data.value.includes(item[1].filename)
        )

        if (file) {
          this.files[file[0]].value = data.value
        }
      }
    },
    onFileAdded(file) {
      try {
        this.files[file.upload.uuid] = {
          filename: file.upload.filename,
          value: JSON.parse(file.xhr.responseText).path
        }
      } catch (err) {
        throw new Error(err)
      }
    },
    onFileRemoved(file) {
      if (this.uploadCounter === 0) {
        delete this.files[file.upload.uuid]
      }
    },
    onSubmit() {
      this.uploading = true
      const form = this.$store.getters.getForm(this.formId)
      const fields = form.fields || {}

      Object.entries(this.files).forEach(async file => {
        const momentDate = moment(
          fields.published_at.formattedValue,
          'YYYY-MM-DD HH:mm:ss'
        )
          .subtract(1, 'minute')
          .format('YYYY-MM-DD HH:mm:ss')

        const params = {
          title: file[1].filename,
          file: file[1].value,
          author: fields.author.formattedValue,
          published_at: momentDate,
          [this.parents[0]]: fields[this.parents[0]].formattedValue,
          status: fields.status.formattedValue,
          type: 'node',
          bundle: this.contents[0],
          fields: ['uuid', 'title'],
          langcode: this.$_currentLang
        }

        try {
          await http.post(`content/${this.contents[0]}`, params)
          this.uploadCounter++
        } catch (err) {
          new Error(err)
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.multi-upload-modal-container {
  padding-top: 43px;

  .container {
    padding: var(--spacing-xxl) 10%;
  }

  .ds-title-container {
    text-align: center;
  }

  .ds-loader-container {
    width: initial;
    margin-right: var(--spacing-s);
  }
}
</style>
