/** @odoo-module */

import { AttendeeCalendarController } from "@calendar/views/attendee_calendar/attendee_calendar_controller";
import { patch } from "@web/core/utils/patch";
import { useService } from "@web/core/utils/hooks";
import { useState, onWillStart } from "@odoo/owl";

patch(AttendeeCalendarController.prototype, {
    setup() {
        super.setup(...arguments);
        this.orm = useService("orm");
        this.notification = useService("notification");
        this.fusionState = useState({
            accounts: [],
            syncing: false,
        });
        onWillStart(async () => {
            await this._loadFusionAccounts();
        });
    },

    get fusionAccounts() {
        return this.fusionState.accounts;
    },

    get fusionSyncing() {
        return this.fusionState.syncing;
    },

    async _loadFusionAccounts() {
        try {
            const accounts = await this.orm.call(
                "fusion.calendar.account",
                "get_user_accounts_status",
                [],
            );
            this.fusionState.accounts = accounts;
        } catch {
            this.fusionState.accounts = [];
        }
    },

    async onFusionSyncNow() {
        this.fusionState.syncing = true;
        try {
            const result = await this.orm.call(
                "fusion.calendar.account",
                "sync_current_user",
                [],
            );
            if (result.success) {
                this.notification.add(
                    result.message || "Calendar synced successfully.",
                    { type: "success" },
                );
                await this._loadFusionAccounts();
                await this.model.load();
                this.render(true);
            } else {
                this.notification.add(
                    result.error || "Sync failed.",
                    { type: "danger" },
                );
            }
        } catch (e) {
            this.notification.add(
                "Sync error: " + (e.message || "Unknown error"),
                { type: "danger" },
            );
        } finally {
            this.fusionState.syncing = false;
        }
    },
});
