// https://forum.vuejs.org/t/how-to-use-helper-functions-for-imported-modules-in-vuejs-vue-template/6266/5

import REST from 'vuejs/api/rest-axios'
import Modal from 'vuejs/components/Helper/Modal'
import LoginRegister from 'vuejs/components/Helper/LoginRegister'
import { mapState } from 'vuex'

export default {
  components: {
    Modal,
    LoginRegister
  },
  computed: {
    ...mapState({
      isloggedin: state => state.User.isloggedin,
      isAdherent: state => state.User.isAdherent,
      csrftoken: state => state.User.csrftoken
    })
  },
  methods: {
    closeModal () {
      this.showLoginModal = false
    },
    checkaddtocart (e, variation_id) {
      console.log('checkaddtocart', e, variation_id, this.isloggedin)

      if (!this.isloggedin) {
        // show popup for login or register
        // login or register event will be catched by onLogedin or onRegistered
        // this.showLoginModal = variation_id
        this.showLoginModal(variation_id)
      } else {
        // if already logedin directly goes to cart operations
        this.addtocart(variation_id)
      }
    },
    showLoginModal (variation_id) {
      this.$modal.show(
        LoginRegister,
        // props
        {
          // item: this.item,
          header: 'materio.In order to be able to place your order, please log in or create your account',
          callbackargs: { variation_id: variation_id },
          // close: (variation_id) => { this.closeModal(variation_id) },
          onLogedInBack: (cba) => { this.onLogedIn(cba.variation_id) },
          onRegisteredBack: (cba) => { this.onRegistered(cba.variation_id) }
          // // not really an event
          // // more a callback function passed as prop to the component
          // addNoteId: (id) => {
          //   // no needs to refresh the entire item via searchresults
          //   // plus if we are in article, there is not searchresults
          //   // this.refreshItem({id: this.item.id})
          //   // instead create the note id directly
          //   this.item.note = { id: id }
          // }
        },
        // settings
        {
          name: 'modal-loginregister',
          draggable: false,
          classes: 'vm--modale-loginregister',
          width: '550px',
          height: '400px'
        }
      )
    },
    // event bubbled from modal login form
    onLogedIn (variation_id) {
      console.log('Product: onLogedIn. variation_id', variation_id)
      this.addtocart(variation_id)
    },
    // event bubbled from modal register form
    onRegistered (variation_id) {
      console.log('Product: onRegistered. variation_id', variation_id)
      this.addtocart(variation_id)
    },
    getCarts () {
      // this is bugging on stage
      return REST.get('/cart?_format=json', {}, { 'X-CSRF-Token': this.csrftoken })
        // .then(({ data }) => {
        //   console.log('current user carts: data', data)
        // })
        .catch((error) => {
          console.warn('Issue with get cart', error)
          Promise.reject(error)
        })
    },
    deleteCart (order_id) {
      console.log('deleting cart ', order_id)
      return REST.delete(`/cart/${order_id}/items?_format=json`)
        .then(({ data }) => {
          console.log(`product cart ${order_id} deleted: data`, data)
        })
        .catch((error) => {
          console.warn(`Issue with cart ${order_id} deleting`, error)
          Promise.reject(error)
        })
    },
    clearCarts (data) {
      const promises = []
      // clear each cart as a promise
      for (let i = 0; i < data.length; i++) {
        promises.push(this.deleteCart(data[i].order_id))
      }
      // return all the promises as one
      return Promise.all(promises)
    },
    addtocart (variation_id) {
      console.log('addtocart')

      // transition
      this.$modal.hide('modal-loginregister')
      document.getElementById('main-content').classList.add('loading')

      // handle the cart then redirect to checkout flow
      this.getCarts()
        .then(({ data }) => {
          console.log('current user carts: data', data)
          this.clearCarts(data)
            .then(() => {
              console.log('all carts cleared')
              // fill the cart with new product
              REST.post('/cart/add?_format=json', [{
                purchased_entity_type: 'commerce_product_variation',
                purchased_entity_id: variation_id,
                quantity: this.quantity
              }])
                .then(({ data }) => {
                  console.log('product added to cart: data', data)
                  this.closeModal()
                  // redirect to /cart
                  // window.location.href = "/cart"
                  // TODO: redirect to checkout instead of cart
                  window.location.href = `/checkout/${data[0].order_id}/order_information`
                })
                .catch((error) => {
                  console.warn('Issue with product add to cart', error)
                  document.getElementById('main-content').classList.remove('loading')
                  Promise.reject(error)
                })
            })
        })
    }
  }
}
