<template>
  <article class="product">
    <header>
      <h1 v-html="product.title"/>
    </header>
    <section class="content">
      <div class="description" v-html="product.body"/>
      <!-- <div class="price-description" v-html="product.price_description"/> -->
    </section>
    <aside v-if="!isAdherent">
      <div
        class="variation"
        v-for="variation in product.variations"
        :key="variation.id"
      >
        <div class="variation-description" v-html="variation.description"/>
        <button
          type="button"
          name="addtocart"
          @click.stop="checkaddtocart($event, variation.id)"
        >
          {{ $t("default.Add to cart") }}
        </button>
      </div>

    </aside>

    <Modal
      v-if="showLoginModal"
      @close="closeModal"
      :styles="{width:'500px', height:'300px'}"
    >
      <section id="pricing-modal-login-register">
        <h2>{{ $t("materio.Please login or create a new account to order your access") }}</h2>
        <LoginRegister
          :callbackargs="showLoginModal"
          @onLogedIn="onLogedIn"
          @onRegistered="onRegistered"
        />
      </section>
    </Modal>

  </article>
</template>

<script>

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

let basePath = drupalSettings.path.baseUrl + drupalSettings.path.pathPrefix;

export default {
  name: "Product",
  router,
  props: ['product'],
  data(){
    return {
      quantity: 1,
      showLoginModal:false
    }
  },
  computed: {
    ...mapState({
      isloggedin: state => state.User.isloggedin,
      isAdherent: state => state.User.isAdherent,
      csrftoken: state => state.User.csrftoken
    })
  },
  methods:{
    // ...mapActions({
    //   userLogin: 'User/userLogin'
    // }),
    closeModal () {
      this.showLoginModal = false;
    },
    checkaddtocart(e, variation_id) {
      console.log('checkaddtocart');

      if(!this.isloggedin){
        // show popup for login or register
        // login or register event will be catched by onLogedin or onRegistered
        this.showLoginModal = variation_id
      }else{
        // if already logedin directly goes to cart operations
        this.addtocart(variation_id)
      }
    },
    // 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) {
      let promises = [];
      // clear each cart as a promise
      for (var 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")
      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)
                    Promise.reject(error)
                })
            })
        })
    }
  },
  components: {
    Modal,
    LoginRegister
  }
}
</script>

<style lang="scss" scoped>
</style>
