<template>
  <base-message-form
    @save="sendMessage"
    @cancel="cancel"
    @change-type="model.type = $event"
    :loading="isLoading"
    :types="types"
    :current-type="model.type"
  >
    <template #body>
      <sms-input
        v-if="model.type === messageTypes.sms"
        v-model="model.body"
        :errors="errors"
      />
      <template v-else>
        <feedback-input v-model="model.body" :errors="errors" />
        <file-attach-btn @change="selectFiles" class="q-mt-md" />
        <message-files is-editable :files="model.attachments" class="q-mt-md" />
        <new-message-files :files="files" class="q-mt-md" />
      </template>
    </template>
  </base-message-form>
</template>

<script lang="ts">
import { Component, Prop, Watch } from 'vue-property-decorator'
import { Message } from '@/widgets/messages/types/Message'
import NewMessageFiles from '@/widgets/messages/components/message-form/NewMessageFiles.vue'
import UiInputMaterial from '@/lib-components/form/UiInputMaterial.vue'
import FileAttachBtn from '@/widgets/base/components/message-form/FileAttachBtn.vue'
import MessageFiles from '@/widgets/messages/components/message/MessageFiles.vue'
import BaseMessageForm from '@/widgets/base/components/message/BaseMessageForm.vue'
import CommonMessageForm from '@/widgets/messages/components/message-form/CommonMessageForm'
import SmsInput from '@/widgets/messages/components/message-form/common/SmsInput.vue'
import FeedbackInput from '@/widgets/messages/components/message-form/common/FeedbackInput.vue'

@Component({
  components: {
    FeedbackInput,
    SmsInput,
    MessageFiles,
    FileAttachBtn,
    UiInputMaterial,
    BaseMessageForm,
    NewMessageFiles,
  },
})
export default class EditMessageForm extends CommonMessageForm {
  @Prop({ type: Object, required: true })
  message!: Message

  model: Message = {
    ...this.message,
    attachments: [...this.message.attachments],
  }

  sendMessage() {
    this.isLoading = true

    this.messageModule
      .saveMessage({ ...this.model, files: this.files })
      .then(() => this.save())
      .finally(() => (this.isLoading = false))
  }

  @Watch('message')
  updateModel() {
    this.model = {
      ...this.message,
      attachments: [...this.message.attachments],
    }
  }
}
</script>
