<template>
  <div class="question" v-bind:class="{ 
      'error': isValid == false, 
      'good': isValid == true
    }">
    
    <fieldset class="checkbox">
      <legend v-if="label">{{ label }}</legend>
      <input type="checkbox" 
        :id="inputname" 
        :name="inputname" 
        value="true" 
        :checked="selectedValue"
        @change="validate()"><label :for="inputname"></label>

      <p class="multiline" v-if="description" v-html="description"></p>
      <p class="error-message">{{ validationMessage }}</p>
    </fieldset>
  </div>
</template>

<script>
import Vue from 'vue'

import vRules from 'vanilla-validation'
import { validation } from '../mixins/validation.js'

export default {
  name: 'checkboxinput',
  props: {
    inputname: {
      type: String,
      required: true
    },
    label: String,
    required: Boolean,
    value: Object,
    description: String,
    sectionID: Number
  },
  mixins: [validation],
  data() {
    return {
      selectedValue: null
    }
  },
  created() {
    // We listen for the event on the eventHub
    this.$eventHub.on('validate', (id) => {
      // if validating by section
      if (this.sectionID != undefined) {
          // if the id provided matches section ID then validate
          if (id === this.sectionID) {
            this.validate()
          }
      } else {
        // if not validating by section
        this.validate()
      }
    })
    // if prepopulating set data
    if (this.value !== undefined && this.value.value !== null) {
        this.selectedValue = this.value.value.toString()
    }
  },
  mounted() {
    // if prepopulating validate the data
    if (this.value !== undefined) {
      this.validate('prepopulated')
    }
  },
  methods: {
    emitValue: function(type){
      // get the input ':checked' status
      this.selectedValue = this.$el.querySelector('input').checked
      // emit validated event
      this.$emit(type, { 
        'value': this.selectedValue, 
        'name': this.inputname, 
        'isValid': this.isValid 
      })
    },
    validate: function(type) {
        // get fieldset element for validation
        let elm = this.$el.querySelector('fieldset')
        // check what validations are required
        // and build and array of booleans (these are then checked to see if input is valid)
        let result = [
          // conditional validation rules
          this.required ? vRules.vrule_checkboxTrue(elm) : true
        ]
        
        // check validation result
        // this function is imported from validation mixin
        // if will set the valid status and error message
        this.setValidationStatus(result)

        // default the type to 'validated' if not using prepopulated event type
        let emitType = type !== 'prepopulated' ? 'validated' : type
        // emit the updated value to parent
        this.emitValue(emitType)
    }
  }
}
</script>
