

<template>
    <fieldset
        :class="['question', fieldsetClass, { 
        'error': isValid == false, 
        'good': isValid == true,
        'double-row': doubleRow == true,
        'fixed2': columns == 2,
        'fixed3': columns == 3,
        'fixed4': columns == 4,
        }]"
        v-bind:validate="hasRules"
    >
    <legend v-show="label !== null && label !== ''">{{ label }}</legend>
    <span class="info-message" v-if="helpText !== undefined">{{ helpText }}</span>
    <span class="info-message" v-if="helpHTML !== undefined" v-html="helpHTML"></span>
    <template v-for="item in options">
        <input type="radio"
            :value="item.value"
            :id="inputname + '_' + item.value"
            :name="inputname"
            :checked="selectedValue.toString() === item.value.toString()" 
            @change="validate()"
            :key="inputname + '_' + item.value + '_input'"  
            ><label
                :key="inputname + '_' + item.value + '_label'" 
                :for="inputname + '_' + item.value"
                :class="item.class"
                v-html="item.name"
            ></label>
    </template>

    <span class="error-message">{{ validationMessage }}</span>
</fieldset>
</template>

<script>
// create event hub for validation events
import Vue from 'vue'
//import EventHub from 'vue-event-hub'
//Vue.use(EventHub)

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

export default {
name: 'buttons-radio',
props: {
    inputname: {
      type: String,
      required: true
    },
    label: String,
    required: Boolean,
    value: Object,
    options: Array,
    fieldsetClass: String,
    helpText: String,
    helpHTML: String,
    columnCount: Number,
    sectionID: Number,
    customErrors: {
      type: Object,
      default: function () { 
        return {
          required: null
        }
      }
    }
},
mixins: [validation],
data() {
    return {
        selectedValue: '',
        hasRules: false,
        columns: 3,
        doubleRow: false,
    }
},
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
    }
},
mounted() {
    // if prepopulating validate the data
    if (this.value !== undefined && this.value.value !== null) {
        this.validate('prepopulated')
    }
    // work out column widths
    if(this.columnCount === null || this.columnCount === undefined) {
        if(this.options.length == 2){
            this.columns = 2
            if(this.options.length > 2)
                this.doubleRow = true
        } else if (this.options.length >= 3 && this.options.length <= 6 && this.options.length != 4){
            this.columns = 3
            if(this.options.length > 3)
                this.doubleRow = true
        } else if(this.options.length >= 4){
            this.columns = 4
            if(this.options.length > 4)
                this.doubleRow = true
        }
    } else {
        this.columns = this.columnCount
    }
},
methods: {
    emitValue: function(type){
        let isBool = (this.selectedValue === 'true' || this.selectedValue === 'false')
        let tempValue = isBool ? this.selectedValue === 'true' : this.selectedValue
        
        // emit validated event
        this.$emit(type, { 
            'value': tempValue, 
            'name': this.inputname, 
            'isValid': this.isValid 
        })
    },
    validate: function(type) {
        // get component element
        let element = this.$el
        // 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_btn_required(element, this.customErrors.required) : true,
        ]

        // check validation result
        // this function is imported from validation mixin
        // if will set the valid status and error message
        this.setValidationStatus(result)
        
        if (this.isValid){
            this.selectedValue = element.querySelector(':checked') ? element.querySelector(':checked').value : ''
        }
        
        // 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>
