<template>
    <div class="input-group" :title="prettyDescription">
        <label class="input-group-text form-control-inline form-control-sm text-light border-dark bg-dark badge">
            {{ property.name }} =
        </label>
        <input type="number" min="0"
               class="form-control form-control-inline form-control-sm text-light border-dark bg-dark badge"
               placeholder="Enter value" @input.prevent="inputChange"
               :value="localValue" :style="inputStyle"/>
        <span class="input-group-text form-control-sm text-light border-dark bg-dark badge"
              v-if="property.unit_symbol" :title="(property.unit_name?property.unit_name:property.unit_symbol)">
                {{ property.unit_symbol }}
            </span>
        <span class="input-group-text form-control-sm text-light border-dark bg-dark badge pl-1">
            <b-icon-x-circle @click="removeProperty()"></b-icon-x-circle>
        </span>
    </div>
</template>

<style scoped>
.form-control-inline {
    display: inline;
    width: auto;
}

.input-group {
    width: initial;
}

.form-control.badge {
    border: 0;
}

.input-group-text.badge {
    padding: .3rem 0rem;
}

.input-group .badge:first-child {
    padding-left: 0.5rem;
}

.input-group .badge:last-child {
    padding-right: 0.5rem;
}

input.badge {
    --width: 0em;
    min-height: calc(1.2rem);
    line-height: 1;
    min-width: calc(var(--width) + 1.35em + 18px);
    width: 0;
    text-align: left;
}

input[type=number].badge {
}

input.badge:empty {
    display: initial;
}
</style>

<script>
import * as BIcons from "bootstrap-icons-vue";
import {mapActions, mapState} from "vuex";

export default {
    name: "PropertyBadge",
    components: {
        ...BIcons
    },
    data() {
        return {
            localValue: this.property.value
        }
    },
    props: {
        property: {
            type: Object,
            required: true
        }
    },
    property: {
        prop: "property",
        event: "modelChange"
    },
    computed: {
        prettyDescription() {
            var d = this.property.description ? this.property.description : this.property.name
            if (this.property.unit_name) {
                d += " (" + this.property.unit_name + ")"
            }
            return (d || "").replace(/<[^>]*>?/gm, '')
        },
        inputStyle() {
            const w = this.property.value ? Math.max(1, this.property.value.toString().length) : 1
            if (this.property.value === undefined) {
                console.log("No value for property", this.property)
            }
            return {
                "--width": w + "ex"
            }
        }
    },
    methods: {
        inputChange(event) {
            this.localValue = event.target.value
            this.$emit("modelChange", {...this.property, value: this.localValue})
        },
        removeProperty() {
            this.$emit("remove")
        }
    },
}
</script>