fetch method

Fetch a resource from the other end Class GUID Resource IdGuid classId

Implementation

AsyncReply<DistributedResource> fetch(int id) {
  var resource = _resources[id];
  var request = _resourceRequests[id];

  if (request != null) {
    // dig for dead locks
    if (resource != null) // dead lock
      return AsyncReply<DistributedResource>.ready(resource);
    else
      return request;
  } else if (resource != null && !resource.suspended)
    return new AsyncReply<DistributedResource>.ready(resource);

  var reply = new AsyncReply<DistributedResource>();
  _resourceRequests.add(id, reply);

  (sendRequest(IIPPacketAction.AttachResource)..addUint32(id)).done()
    ..then((rt) {
      if (rt != null) {
        // @TODO: Generator code
        DistributedResource dr;

        if (resource == null) {
          var template =
              Warehouse.getTemplateByClassId(rt[0], TemplateType.Wrapper);
          if (template?.definedType != null) {
            dr = Warehouse.createInstance(template?.definedType as Type);
            dr.internal_init(this, id, rt[1], rt[2]);
          } else {
            dr = new DistributedResource();
            dr.internal_init(this, id, rt[1], rt[2]);
          }
        } else
          dr = resource;

        //var dr = resource ?? new DistributedResource(this, id, rt[1], rt[2]);

        getTemplate(rt[0] as Guid)
          ..then((tmp) {
            //print("New template ");

            var d = rt[3] as DC;

            // ClassId, ResourceAge, ResourceLink, Content
            if (resource == null) {
              Warehouse.put(id.toString(), dr, this, null, tmp)
                ..then((ok) {
                  Codec.parsePropertyValueArray(d, 0, d.length, this)
                      .then((ar) {
                    //print("attached");
                    dr.internal_attach(ar);
                    _resourceRequests.remove(id);
                    reply.trigger(dr);
                  });
                })
                ..error((ex) => reply.triggerError(ex));
            } else {
              Codec.parsePropertyValueArray(d, 0, d.length, this).then((ar) {
                //print("attached");
                if (ar != null) dr.internal_attach(ar);
                _resourceRequests.remove(id);
                reply.trigger(dr);
              });
            }
          })
          ..error((ex) {
            reply.triggerError(ex);
          });
      } else {
        reply.triggerError(Exception("Null response"));
      }
    })
    ..error((ex) {
      reply.triggerError(ex);
    });

  return reply;
}