<script>

import Vue from 'vue'
import { mapState, mapActions } from 'vuex'
import { MA } from 'vuejs/api/ma-axios'

export default {
  name: "LoginForm",
  data: () => ({
    form:null,
    mail:null,
    password:null
  }),
  methods: {
    ...mapActions({
      userLogin: 'User/userLogin'
    }),
    getLoginForm(){
      // Form through ajax is provided by materio_user drupal custom module
      // vuejs attributes a inserted by form alter in same module
      MA.get(`/materio_user/login_form`)
        .then(({data}) => {
          console.log("getLoginForm data");
          this.form = Vue.compile(data.rendered)
          this.$options.staticRenderFns = [];
          this._staticTrees = [];
          this.form.staticRenderFns.map(fn => (this.$options.staticRenderFns.push(fn)));
        })
        .catch(( error ) => {
          console.warn('Issue with getLoginForm', error)
        })
    },
    login () {
      this.userLogin({
        mail: this.mail,
        pass: this.password
      }).then( () => {
          console.log('logedin from login component');
          this.$emit('onLogedIn')
        }
      ).catch(( error ) => {
        console.warn('Issue with login from login component', error)
        Promise.reject(error)
      })
    }
  },
  beforeMount () {
    if(!this.form){
      this.getLoginForm()
    }
  },
  mounted(){
    // console.log('LoginBlock mounted');
    Drupal.attachBehaviors(this.$el);
  },
  render(h) {
    // console.log('LoginBlock render');
    if(!this.form){
      // console.log('LoginBlock render NAN');
      return h('span', 'Loading ...')
    }else{
      // console.log('LoginBlock render template');
      return this.form.render.call(this)
    }
  }
}
</script>

<style lang="scss" scoped>
  .form-item,
  .form-actions{
    display:inline-block;
    max-width:32%;
    margin:0;
  }
  input{
    box-sizing:border-box;
    max-width:100%;
  }
  div.description{
    display:none;
  }
  .form-item-persistent-login{
    display:none;
  }
</style>
