<template>
  <article class="product">
    <header>
      <h1 v-html="product.title" />
    </header>
    <section class="content">
      <div class="description" v-html="product.field_description" />
      <span class="price">{{ product.price__number }}</span>
    </section>
    <aside class="">
      <input
        v-if="product.field_multiple"
        v-model="quantity"
        placeholder="quantity"
        type="text"
        name="quantity"
        value="1"
      />
      <button
        type="button"
        name="addtocart"
        @click.stop="checkaddtocart"
      >
        Commander
      </button>
    </aside>
    <Modal
      v-if="login"
    >
      i'm a modal
    </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'

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

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

      if(!this.isloggedin){
        // TODO: show popup login or register
        this.login = true
        // TODO: rest login or register
        // TODO: rest login
        // TODO: this.addtocart()
      }else{
        this.addtocart()
      }
    },
    addtocart () {
      console.log("addtocart")

      REST.post(`/cart/add?_format=json`, [{
        "purchased_entity_type": "commerce_product_variation",
        "purchased_entity_id": this.product.variation_id,
        "quantity": this.quantity
      }])
        .then(({ data }) => {
          console.log('product add to cart REST: data', data)
        })
        .catch(( error ) => {
            console.warn('Issue with pricing', error)
            Promise.reject(error)
        })

    }
  },
  components: {
    Modal
  }
}
</script>

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