<template>
  <div id="feedback" class="fixed-bottom">
    <transition-group name="fade">
      <SmartModal v-for="(error, index) in errors" :key="index" :has-footer="false" :error="true" @close="close(errors, index)">
        <template #header>
          An error as occured
        </template>
        <template #body>
          <div class="row">
            <div class="col-sm-12 text-light fs-6">
              {{cuteErrorMessage(error)}}
            </div>
          </div>
        </template>
      </SmartModal>
    </transition-group>
    <div v-for="(warning, index) in warnings" :key="index" class="alert alert-warning alert-dismissible fade show" role="alert">
      {{warning}}
    </div>
    <transition-group name="fade">
      <div v-for="(success, index) in successes" :key="index" class="alert alert-success alert-dismissible fade show" role="alert">
        {{success}}
      </div>
    </transition-group>
  </div>
</template>

<script>

import {watch} from 'vue'
import SmartModal from '@/components/SmartModal'
import useFeedback from './hooks/feedback'
import { useI18n } from 'vue-i18n'

export default {
  setup: (_props) => {
    const { t } = useI18n()
    const {successes, warnings, errors} = useFeedback()

    const close = function(arr, index){
      arr.splice(index, 1)
    }

    const cuteErrorMessage = (error) => {
      let cuteMessage = 'unexpected'

      if(error.toString().includes('already exists.')){
        cuteMessage = 'already_exists'
      }else if(error.toString().includes('Ensure this value has at most')){
        cuteMessage = 'invalid_form'
      }

      return t('errors.'+cuteMessage)
    }

    watch(successes.value, function(){
      setTimeout(function(){
        successes.value.shift()
      }, 3000)
    })

    return { successes, warnings, errors, close, cuteErrorMessage}
  },
  components: {SmartModal},
}
</script>
