<template>
</template>
<script setup lang="ts">
    import { useMessage } from 'naive-ui'
    import { onUpdated, onMounted } from 'vue'

    const message = useMessage()
    const props = defineProps(['messages'])

    onMounted(() => {
        displayNewMessages(props.messages)
    })

    onUpdated(() => {
        displayNewMessages(props.messages)
    })

    function displayNewMessages(messages: any) {

        let output: Array<Object> = []

        output = flattenObject(removeValidationErrors(messages))

        output?.forEach((item: any) => {
            for (let key in item) {
                switch (key){
                    case 'error':
                        message.error(
                            translateError(item[key]),
                            { closable: true }
                        )
                        break
                    case 'warning':
                        message.warning(
                            translateError(item[key]),
                            { closable: true}
                        )
                        break
                    case 'info':
                        message.info(
                            translateError(item[key]),
                            { closable: true }
                        )
                        break
                    default:
                        message.warning(
                            translateError(item[key]),
                            { closable: true }
                        )
                }
            }
        })
    }   

    function removeValidationErrors(input: any) {

        if(input === null || !input.hasOwnProperty("errors")) return input
    
        const { errors: _, ...output } = (input as any)
        return output
    }

    function flattenObject(input: Object) {
        if (input === null) return input

        return Object.values(input).map((value) => Object.entries(value)).flat().reduce((acc: Array<Object>, [key, value]) => {
            acc.push({[key]: value});
            return acc;
        }, []);
    }

    function translateError(errorMsg: string) {
        switch(errorMsg.split(":")[0]) {
            case 'E_INVALID_AUTH_PASSWORD':
                return "Falsches Passwort eingegeben."
            case 'E_INVALID_AUTH_UID':
                return "Benutzername nicht gefunden"
            case 'E_AUTHORIZATION_FAILURE':
                return 'Rechte unzureichend um diese Aktion auszuführen.'
        }
        return errorMsg
    }
</script>