<template>
    <div id="regex-create">
        <div class="regex-header">
            <template v-if=" ! regex">
                <h1> New regex searcher </h1>

                <InputText v-model="name"
                       type="text"
                       placeholder="Enter searcher name"
                       class="input">
                </InputText>
            </template>

            <Button @click="onSave" :disabled="( ! name && ! regex) || ! pattern">
                Save
            </Button>
        </div>

        <div class="regex-box">
            <div class="main">
                <pattern-box v-model="pattern"></pattern-box>

                <text-box :pattern="pattern"
                          :flags="flags">
                </text-box>

                <flags v-model="flags"></flags>
            </div>

            <aside>
                <side-bar></side-bar>
            </aside>
        </div>
    </div>
</template>

<script lang="ts">
import {Component, Prop, Vue} from "vue-property-decorator";
import TextBox from './TextBox.vue';
import PatternBox from './PatternBox.vue';
import Flags from './Flags.vue';
import SideBar from './SideBar.vue';

@Component({
    name: 'RegexCreate',

    components: {
        TextBox,
        PatternBox,
        Flags,
        SideBar,
    },
})

export default class Create extends Vue {
    private name: string = '';
    private pattern: string = '';
    private flags: Array<string> = ['g', 'i'];

    @Prop({
        default: '',
    })
    public readonly regex!: string;

    onSave() {
        if ( ! this.regex) {
            this.save();

            return;
        }

        this.$emit('updated', this.pattern);
    }

    async save() {
        try {
            const { data } = await (window as any).axios.post('/regex', {
                name: this.name,
                expression: this.pattern,
            });

            this.$toast.add({
                severity: 'success',
                summary: 'Searcher created.',
                life: 1000,
            });

            setTimeout(() => {
                window.location.href = `/searchers/${data.searcher.id}`;
            }, 1000);
        } catch (e) {
            console.log(e);
            console.log('Something went wrong.');
        }
    }

    created() {
        if (this.regex) {
            this.pattern = this.regex;
        }
    }
};
</script>
