import { action, computed, makeObservable, observable } from 'mobx'
import DraftsModel from './DraftsModel'

class DraftItemModel {
  constructor({
    draftsModel,
    section,
    orderItemId,
    orderItemFriendlyId,
    quantity,
    description,
    editUrl,
    creationDate,
    thumbnailUrl,
    product,
    subItems,
    validations,
  }) {
    this._draftsModel = draftsModel
    this.section = section
    this.orderItemId = orderItemId
    this.orderItemFriendlyId = orderItemFriendlyId
    this.quantity = quantity
    this.description = description || ''
    this.editUrl = editUrl
    this.creationDate = creationDate
    this.thumbnailUrl = thumbnailUrl
    this.product = product
    this.subItems = subItems || []
    this.deleting = false
    this.saving = false
    this.validations = validations || []

    makeObservable(this, {
      section: observable,
      description: observable,
      deleting: observable,
      saving: observable,
      validations: observable,
      delete: action,
      save: action,
      updateDescription: action,
      setDeleting: action,
      setSaving: action,
      isSaved: computed,
      isLatest: computed,
      isProductAvailable: computed,
      hasSubItems: computed,
    })
  }

  async delete(options = {}) {
    this.setDeleting(true)
    try {
      await this._draftsModel.deleteItem(this, options)
    } catch (error) {
      this.setDeleting(false)
      throw error
    }
  }

  async save(description, options = {}) {
    this.setSaving(true)
    try {
      await this._draftsModel.saveItem(this, description, options)
    } finally {
      this.setSaving(false)
    }
  }

  updateDescription(description) {
    this.description = description
  }

  setDeleting(value) {
    this.deleting = value
  }

  setSaving(value) {
    this.saving = value
  }

  continue() {
    if (this.isProductAvailable && this.editUrl) {
      this._draftsModel.navigate(this.editUrl)
    }
  }

  get isSaved() {
    return this.section === DraftsModel.DRAFT_SECTIONS.SAVED
  }

  get isLatest() {
    return this.section === DraftsModel.DRAFT_SECTIONS.LATEST
  }

  get isProductAvailable() {
    return this.product?.isAvailable !== false
  }

  get hasSubItems() {
    return this.subItems && this.subItems.length > 0
  }
}

export default DraftItemModel
