<template>
    <ModalForm ref="form" :panel="driver" :values="values" :prerequest="false" @resolve="resolve" />
</template>

<script>
import { ModalForm } from '@essentials/core/components';
import { set, unique } from '@essentials/core/util';

export default {
    name: 'AuthModal',

    components: {
        ModalForm,
    },

    inject: {
        AuthsManager: {
            from: 'EssentialsAuths',
        },
    },

    provide() {
        return {
            AuthModal: this,
        };
    },

    props: {
        driver: {
            type: Object,
        },
        scopes: {
            type: Array,
        },
        values: {
            type: Object,
        },
    },

    events: {
        'yooessentials-prerequest'(e) {
            e.params[0]['auth'] = this.$refs.form.draft;
            e.params[0]['requiredScopes'] = this.scopes;
        },
    },

    methods: {
        updateValues(values) {
            for (const key in values) {
                let value = values[key];
                set(this.values, key, value);
            }
        },

        connect() {
            const scopes = this.$refs.form.draft.scopes;

            this.AuthsManager.oauth(this.driver.name, this.scopes).then((oauth) => {
                for (const prop in oauth) {
                    let value = oauth[prop];

                    // merge scopes
                    if (prop === 'scopes') {
                        value = unique([...(scopes ?? []), ...value]);
                    }

                    set(this.$refs.form.draft, prop, value);
                }

                // auto save the auth giving some time to the ui
                setTimeout(() => {
                    this.$refs.form.loading = false;
                    this.$refs.form.save();
                }, 500);
            });
        },

        resolve(values) {
            const auth = this.AuthsManager.save(values);

            this.updateValues(auth);
            this.$emit('resolve', auth);
        },
    },
};
</script>
