<template>
    <form @submit.prevent="submit">
        <slot></slot>
    </form>
</template>

<script lang="ts">
    import _ from "lodash";
    import Vue from "vue";

    export type Input = {
        validate(): boolean;
        focusElement(): void;
    };

    export default Vue.extend({
        name: 'FormComponent',
        data() {
            return {
                inputs: [] as Input[],
            };
        },
        computed: {},
        watch: {},
        methods: {
            submit() {
                this.$emit('submit', this.validate());
            },
            validate(): boolean {
                let value = true;
                for (let input of this.inputs) {
                    if (!input.validate()) {
                        value = false;
                        input.focusElement();
                    }
                }
                return value;
            },
        },
        mounted() {
            // @ts-ignore
            this.inputs = _.filter(this.$children, (component: Input) => {
                return component.validate !== undefined;
            });
        },
    });
</script>

<style scoped>

</style>
