<template>
    <div class="uk-margin-remove-first-child">
        <div v-if="auths.length">
            <ul class="uk-nav uk-nav-default yo-sidebar-marginless yo-nav-iconnav">
                <ResourceListItem
                    v-for="{ auth, driver, meta, error, warning, expiresSoon } in auths"
                    :key="auth.id"
                    :title="auth.name || auth.account || auth.username || (driver && driver.title) || $t('Unknown')"
                    :icon="driver && driver.icon"
                    :error="error || warning"
                    :meta="meta"
                    :actions="
                        [
                            'delete',
                            expiresSoon && {
                                title: $t('Requires Re-Authentication'),
                                emit: 'edit',
                                icon: 'warning',
                                class: 'uk-text-danger',
                                stack: true,
                            },
                        ].filter(Boolean)
                    "
                    :editable="!error"
                    @edit="edit(auth)"
                    @delete="trash(auth)"
                >
                    <template v-if="!driver" #icon>
                        <span class="uk-margin-small-right" uk-icon="question" ratio="1.2"></span>
                    </template>

                    <template v-else-if="!driver.icon && driver.type !== 'oauth'" #icon>
                        <span class="uk-margin-small-right" uk-icon="lock" ratio="1.2"></span>
                    </template>
                </ResourceListItem>
            </ul>

            <p class="uk-text-muted">
                {{
                    $t(
                        'Connected Accounts and other authentication-related keys used with Sources, Storages or Form Actions.'
                    )
                }}
            </p>
        </div>

        <div v-else class="uk-text-center">
            <p>
                {{
                    $t(
                        'Connected Accounts and other authentication-related keys used with Sources, Storages or Form Actions will appear here.'
                    )
                }}
            </p>
        </div>
    </div>
</template>

<script>
import { ResourceListItem } from '@essentials/core/components';
import AuthModal from './AuthModal.vue';
import add from 'date-fns/add';

export default {
    name: 'AuthSection',

    components: {
        ResourceListItem,
    },

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

    computed: {
        drivers() {
            return this.AuthsManager.drivers;
        },

        auths() {
            return this.AuthsManager.auths.map((auth) => {
                const driver = this.drivers?.[auth.driver];

                if (!driver) {
                    return { auth, error: 'Auth Driver Not Found' };
                }

                if (driver.type === 'oauth' && !auth.scopes) {
                    return { auth, driver, warning: 'Missing Authorization' };
                }

                const res = { auth, driver };

                if (driver.accessTokenThreshold && auth.expiresAt) {
                    const expiresAt = new Date(auth.expiresAt?.date || auth.expiresAt * 1000);
                    const expiresIn = expiresAt.valueOf() - new Date().valueOf();
                    const formated = expiresAt.toLocaleString().split(',')[0];

                    if (expiresIn <= 0) {
                        return { ...res, warning: 'Expired ' + formated };
                    }

                    let [num, unit] = driver.accessTokenThreshold.split(' ');

                    // pluralize
                    if (unit[unit.length + 1] !== 's') {
                        unit = `${unit}s`;
                    }

                    const threshold = add(new Date(), { [unit]: num });
                    const thresholdIn = threshold.valueOf() - new Date().valueOf();

                    res.expiresSoon = expiresIn < thresholdIn;
                    res.meta = 'Expires ' + formated;
                }

                return res;
            });
        },
    },

    methods: {
        edit(auth) {
            const driver = this.AuthsManager.drivers[auth.driver];

            return this.$modal(AuthModal, {
                driver,
                values: auth,
                scopes: Object.keys(driver?.scopes || {}),
            })
                .show()
                .then((auth) => {
                    auth && this.AuthsManager.save(auth);
                });
        },

        trash(auth) {
            this.AuthsManager.remove(auth);
        },
    },
};
</script>
