

(function () {
  'use strict';

  var _nextReq = 1;
  var _pending = {};   

  window.VizChannel = {
    bridge: null,
    


    cloud: null,

    
    connect: function (handlers, done) {
      new QWebChannel(qt.webChannelTransport, function (channel) {
        var b = channel.objects.bridge;
        window.VizChannel.bridge = b;
        if (handlers.onInit)   b.sig_init.connect(function (s) { handlers.onInit(JSON.parse(s)); });
        if (handlers.onState)  b.sig_state.connect(function (s) { handlers.onState(JSON.parse(s)); });
        if (handlers.onLocale) b.sig_locale.connect(function (s) { handlers.onLocale(JSON.parse(s)); });
        

        if (handlers.onSceneWhere) b.sig_scene_where.connect(function (s) { handlers.onSceneWhere(JSON.parse(s)); });
        if (handlers.extra) handlers.extra(b);

        var c = channel.objects.cloudbridge;
        if (c) {
          window.VizChannel.cloud = c;
          if (handlers.onCloudAuth)   c.sig_cloud_auth.connect(function (s) { handlers.onCloudAuth(JSON.parse(s)); });
          if (handlers.onCloudList)   c.sig_cloud_list.connect(function (s) { handlers.onCloudList(JSON.parse(s)); });
          if (handlers.onCloudSaved)  c.sig_cloud_saved.connect(function (s) { handlers.onCloudSaved(JSON.parse(s)); });
          if (handlers.onCloudDone)   c.sig_cloud_done.connect(function (s) { handlers.onCloudDone(JSON.parse(s)); });
          if (handlers.onCloudPrompt) c.sig_cloud_prompt.connect(function (s) { handlers.onCloudPrompt(JSON.parse(s)); });
          if (handlers.onCloudProgress) c.sig_cloud_progress.connect(function (s) { handlers.onCloudProgress(JSON.parse(s)); });
        }

        if (done) done(b);
        b.ready();
      });
    },

    
    request: function (cb) {
      var id = _nextReq++;
      _pending[id] = cb;
      return id;
    },

    resolve: function (payload) {
      var cb = _pending[payload.req_id];
      if (!cb) return;
      delete _pending[payload.req_id];
      



      if (payload.dropped) return;
      cb(payload);
    },

    log: function (msg) {
      if (window.VizChannel.bridge) window.VizChannel.bridge.js_log(String(msg));
    }
  };
})();
