/** @odoo-module **/

import { patch } from "@web/core/utils/patch";
import { PhoneField } from "@web/views/fields/phone/phone_field";
import { rpcBus } from "@web/core/network/rpc";

patch(PhoneField.prototype, {
    onClickCall(ev) {
        if (window.RCAdapter) {
            ev.preventDefault();
            ev.stopPropagation();
            const phoneNumber = this.props.record.data[this.props.name];
            if (phoneNumber) {
                window.RCAdapter.clickToCall(phoneNumber, true);
            }
            return;
        }
        return super.onClickCall(...arguments);
    },
});

rpcBus.addEventListener("RPC:RESPONSE", (ev) => {
    const { result } = ev.detail;
    if (!result || typeof result !== "object" || !window.RCAdapter) {
        return;
    }
    const infos = result.infos;
    if (!infos || !infos.rc_action || !infos.rc_phone_number) {
        return;
    }
    const { rc_action, rc_phone_number } = infos;
    if (rc_action === "call") {
        window.RCAdapter.clickToCall(rc_phone_number, true);
    } else if (rc_action === "sms") {
        window.RCAdapter.clickToSMS(rc_phone_number);
    }
});
