<template>
    <NcSettingsSection :name="t('settings', 'Background jobs')" :description="t(
        'settings',
        `For the server to work properly, it\'s important to configure background jobs correctly. Cron is the recommended setting. Please see the documentation for more information.`,
    )" :doc-url="backgroundJobsDocUrl">

        <template v-if="lastCron !== 0">
            <NcNoteCard v-if="oldExecution" type="danger">
                {{ t('settings', `Last job execution ran {time}. Something seems wrong.`, {
                    time: relativeTime,
                    timestamp: lastCron
                }) }}
            </NcNoteCard>

            <!-- <NcNoteCard v-else-if="longExecutionCron" type="warning">
                {{ t('settings', `Some jobs have not been executed since {maxAgeRelativeTime}. Please consider increasing the execution frequency.`, {maxAgeRelativeTime}) }}
            </NcNoteCard> -->


            <NcNoteCard v-else type="success">
                {{ t('settings', 'Last job ran {relativeTime}.', { relativeTime }) }}
            </NcNoteCard>
        </template>

        <NcNoteCard v-else type="danger">
            'Background job did not run yet!'
        </NcNoteCard>


    </NcSettingsSection>
</template>

<script lang="ts">
import { usePage } from '@inertiajs/vue3';
import { loadState } from '@/utils/initialState';
import { showError } from '@/utils/toast';
// import { generateOcsUrl } from '@nextcloud/router';
// import { confirmPassword } from '@nextcloud/password-confirmation';
import axios from 'axios';
import dayjs from '@/utils/dayjs';

import NcNoteCard from '@/Components/NCNoteCard.vue';
import NcSettingsSection from '@/Components/NcSettingsSection.vue';
import { translate as t } from '@/utils/tethyscloud-l10n';
// import { useLocaleStore } from '@/Stores/locale';

// import '@nextcloud/password-confirmation/dist/style.css';

// const lastCron: number = 1723807502; //loadState('settings', 'lastCron'); //1723788607
const cronMaxAge: number = 1724046901;//loadState('settings', 'cronMaxAge', 0); //''
const backgroundJobsMode: string = loadState('settings', 'backgroundJobsMode', 'cron'); //cron
const cliBasedCronPossible = loadState('settings', 'cliBasedCronPossible', true); //true
const cliBasedCronUser = loadState('settings', 'cliBasedCronUser', 'www-data'); //www-data
const backgroundJobsDocUrl: string = loadState('settings', 'backgroundJobsDocUrl'); //https://docs.nextcloud.com/server/29/go.php?to=admin-background-jobs

// await loadTranslations('settings');

export default {
    name: 'BackgroundJob',

    components: {
        NcSettingsSection,
        NcNoteCard,
    },

    data() {
        return {
            // lastCron: 0,
            cronMaxAge: cronMaxAge,
            backgroundJobsMode: backgroundJobsMode,
            cliBasedCronPossible: cliBasedCronPossible,
            cliBasedCronUser: cliBasedCronUser,
            backgroundJobsDocUrl: backgroundJobsDocUrl,
            // relativeTime: dayjs(this.lastCron * 1000).fromNow(),
            // maxAgeRelativeTime: dayjs(cronMaxAge * 1000).fromNow(),
            t: t,
        };
    },
    computed: {
        lastCron(): number {
            return usePage().props.lastCron as number;

        },
        relativeTime() {
            return dayjs.unix(this.lastCron).fromNow(); // Calculate relative time for lastCron
        },
        maxAgeRelativeTime() {
            return dayjs.unix(this.cronMaxAge).fromNow(); // Calculate relative time for cronMaxAge
        },
        cronLabel() {
            let desc = 'Use system cron service to call the cron.php file every 5 minutes.';
            if (this.cliBasedCronPossible) {
                desc +=
                    '<br>' +
                    'The cron.php needs to be executed by the system account "{user}".', { user: this.cliBasedCronUser };
            } else {
                desc +=
                    '<br>' +

                    'The PHP POSIX extension is required. See {linkstart}PHP documentation{linkend} for more details.',
                {
                    linkstart:
                        '<a target="_blank" rel="noreferrer nofollow" class="external" href="https://www.php.net/manual/en/book.posix.php">',
                    linkend: '</a>',
                }
            }
            return desc;
        },
        oldExecution() {
            return (dayjs().unix() - this.lastCron) > 600; // older than 10 minutes
        },

        longExecutionCron() {
            //type of cron job and greater than 24h
            // let test = dayjs.unix(this.cronMaxAge).format('YYYY-MM-DD HH:mm:ss');
            return (dayjs().unix()  - this.cronMaxAge) > 24 * 3600 && this.backgroundJobsMode === 'cron';
        },
    },
    methods: {
        async onBackgroundJobModeChanged(backgroundJobsMode: string) {
            const url = generateOcsUrl('/apps/provisioning_api/api/v1/config/apps/{appId}/{key}', {
                appId: 'core',
                key: 'backgroundjobs_mode',
            });

            // await confirmPassword();

            try {
                const { data } = await axios.post(url, {
                    value: backgroundJobsMode,
                });
                this.handleResponse({
                    status: data.ocs?.meta?.status,
                });
            } catch (e) {
                this.handleResponse({
                    errorMessage: t('settings', 'Unable to update background job mode'),
                    error: e,
                });
            }
        },
        async handleResponse({ status, errorMessage, error }) {
            if (status === 'ok') {
                await this.deleteError();
            } else {
                showError(errorMessage);
                console.error(errorMessage, error);
            }
        },
        async deleteError() {
            // clear cron errors on background job mode change
            const url = generateOcsUrl('/apps/provisioning_api/api/v1/config/apps/{appId}/{key}', {
                appId: 'core',
                key: 'cronErrors',
            });

            // await confirmPassword();

            try {
                await axios.delete(url);
            } catch (error) {
                console.error(error);
            }
        },
    },
};
</script>

<style lang="css" scoped>
.error {
    margin-top: 8px;
    padding: 5px;
    border-radius: var(--border-radius);
    color: var(--color-primary-element-text);
    background-color: var(--color-error);
    width: initial;
}

.warning {
    margin-top: 8px;
    padding: 5px;
    border-radius: var(--border-radius);
    color: var(--color-primary-element-text);
    background-color: var(--color-warning);
    width: initial;
}

.ajaxSwitch {
    margin-top: 1rem;
}
</style>
