/** @odoo-module **/

import { registry } from "@web/core/registry";
import { useService } from "@web/core/utils/hooks";
import { Component, onMounted, onWillUnmount, useState } from "@odoo/owl";

class PoyntPollAction extends Component {
    static template = "fusion_poynt.PoyntPollAction";
    static props = ["*"];

    setup() {
        this.orm = useService("orm");
        this.actionService = useService("action");
        this.state = useState({ seconds: 0, message: "" });

        const wizardId = this.props.action?.params?.wizard_id;
        this.wizardId = wizardId;

        onMounted(() => {
            if (!this.wizardId) return;
            this._tickTimer = setInterval(() => this.state.seconds++, 1000);
            this._pollTimer = setInterval(() => this._poll(), 5000);
        });

        onWillUnmount(() => this._stop());
    }

    _stop() {
        if (this._tickTimer) { clearInterval(this._tickTimer); this._tickTimer = null; }
        if (this._pollTimer) { clearInterval(this._pollTimer); this._pollTimer = null; }
    }

    async _poll() {
        if (!this.wizardId) { this._stop(); return; }
        try {
            const result = await this.orm.call(
                "poynt.payment.wizard", "action_check_status", [[this.wizardId]],
            );
            if (result && result.type) {
                this._stop();
                this.actionService.doAction(result, { clearBreadcrumbs: true });
            }
        } catch (e) {
            this._stop();
            this.state.message = "Polling stopped due to an error. Use Check Now to retry.";
        }
    }

    async onManualCheck() {
        this.state.message = "";
        if (!this._pollTimer) {
            this._pollTimer = setInterval(() => this._poll(), 5000);
            this._tickTimer = setInterval(() => this.state.seconds++, 1000);
        }
        await this._poll();
    }

    async onCancel() {
        this._stop();
        try {
            await this.orm.call(
                "poynt.payment.wizard", "action_cancel_payment", [[this.wizardId]],
            );
        } catch { /* ignore */ }
        this.actionService.doAction({ type: "ir.actions.act_window_close" });
    }
}

registry.category("actions").add("poynt_poll_action", PoyntPollAction);
