// -*- mode: js; js-indent-level: 4; indent-tabs-mode: nil -*-
/* exported CallsMonitoring */

const { Gio } = imports.gi;

const { loadInterfaceXML } = imports.misc.dbusUtils;
const ObjectManager = imports.misc.objectManager;

const CallIface = loadInterfaceXML('org.gnome.Calls.Call');
const CallProxy = Gio.DBusProxy.makeProxyWrapper(CallIface);

var CallsMonitoring = class {
    constructor(proximityMonitoring) {
        this._proximityMonitoring = proximityMonitoring;

        this._objectManager = new ObjectManager.ObjectManager({
            connection: Gio.DBus.session,
            name: 'org.gnome.Calls',
            objectPath: '/org/gnome/Calls',
            knownInterfaces: [CallIface],
            onLoaded: this._onLoaded.bind(this),
        });
        this._nActiveCalls = 0;
    }

    _onLoaded() {
        const callProxies = this._objectManager.getProxiesForInterface('org.gnome.Calls.Call');
        for (const proxy of callProxies)
            this._addCall(proxy);

        this._objectManager.connect('object-added', (objectManager, objectPath) => {
            if (objectPath.startsWith('/org/gnome/Calls/Call'))
                this._addCall(this._objectManager.getProxy(objectPath, 'org.gnome.Calls.Call'));
        });

        this._objectManager.connect('object-removed', (objectManager, objectPath) => {
            if (objectPath.startsWith('/org/gnome/Calls/Call'))
                this._removeCall(this._objectManager.getProxy(objectPath, 'org.gnome.Calls.Call'));
        });
    }

    _addCall(callProxy) {
        log("CALLSMONITORING: call added n " + this._nActiveCalls + " state " + callProxy.State);

        callProxy.connect('g-properties-changed', (proxy, properties) => {
            for (const prop in properties.deepUnpack()) {
            log("SENSORDAEMON: call notify " + prop + " state " + callProxy.State);
                if (prop !== 'State')
                    return;

                if (callProxy.State === 1) {
                    this._nActiveCalls++;

                    if (this._nActiveCalls === 1)
                        this._proximityMonitoring.enableMonitoring();
                } else if (callProxy.State === 7) {
                    this._nActiveCalls--;

                    if (this._nActiveCalls === 0) {
                        this._proximityMonitoring.stopMonitoring();
                    }
                }
            } 
        });

        if (callProxy.State === 1) {
            this._nActiveCalls++;

            if (this._nActiveCalls === 1) {
                this._proximityMonitoring.enableMonitoring();
            }
        }

    }

    _removeCall(callProxy) {
        log("SENSORDAEMON: call removed");
        this._nCalls = 0;

        if (this._nCalls === 0) {
            this._proximityMonitoring.stopMonitoring();
        }
    }
};
