<template>
    <div class="relative mb-2">
        <label v-if="label" :for="name" class="pb-2 font-bold text-xl ml-1">{{ label }}</label>
        <select :name="name" v-for="option in options" :key="option.value" v-model="value" :class="'block w-full p-2 ' + errorClassObject()">
            <option value="">----</option>
            <option :value="option.value" v-if="selected === String(option.value)" selected>{{ option.label }}</option>
            <option :value="option.value" v-else>{{ option.label }}</option>
        </select>
        <p class="text-red no-indent m-0" v-text="errorMessage()">Error Here</p>
    </div>
</template>

<script>
export default {
    name: 'SelectorField',
    props: {
        classes: String,
        label: String,
        name: {
            type: String,
            required: true,
        },
        options: Array,
        selected: String,
        required: {
            type: Boolean,
            default: false
        },
        errors: Object,
    },
    data: function () {
        return {
            value: ''
        }
    },
    computed: {
        hasError: function () {
            return this.required && this.errors && this.errors[this.name] && this.errors[this.name].length > 0
        }
    },
    methods: {
        errorMessage: function () {
            if (this.hasError) {
                return this.errors[this.name][0]
            }
        },
        clearErrors: function () {
            if (this.hasError) {
                this.errors[this.name] = null
            }
        },
        errorClassObject: function () {
            if (this.hasError) {
                return 'border-red'
            }
        }
    },
    watch: {
        value: function () {
            this.clearErrors(this.name)
            this.$emit('update:field', this.value)
        }
    }
}
</script>
