package org.skywalking.apm.collector.agentregister.grpc.handler;

import com.google.protobuf.ProtocolStringList;
import io.grpc.stub.StreamObserver;
import org.skywalking.apm.collector.agentregister.application.ApplicationIDService;
import org.skywalking.apm.collector.server.grpc.GRPCHandler;
import org.skywalking.apm.network.proto.Application;
import org.skywalking.apm.network.proto.ApplicationMapping;
import org.skywalking.apm.network.proto.ApplicationRegisterServiceGrpc;
import org.skywalking.apm.network.proto.KeyWithIntegerValue;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @author pengys5
 */
public class ApplicationRegisterServiceHandler extends ApplicationRegisterServiceGrpc.ApplicationRegisterServiceImplBase implements GRPCHandler {

    private final Logger logger = LoggerFactory.getLogger(ApplicationRegisterServiceHandler.class);

    private ApplicationIDService applicationIDService = new ApplicationIDService();

    @Override public void register(Application request, StreamObserver<ApplicationMapping> responseObserver) {
        logger.debug("register application");
        ProtocolStringList applicationCodes = request.getApplicationCodeList();
        for (int i = 0; i < applicationCodes.size(); i++) {
            String applicationCode = applicationCodes.get(i);
            int applicationId = applicationIDService.getOrCreate(applicationCode);

            KeyWithIntegerValue value = KeyWithIntegerValue.newBuilder().setKey(applicationCode).setValue(applicationId).build();
            ApplicationMapping mapping = ApplicationMapping.newBuilder().addApplication(i, value).build();
            responseObserver.onNext(mapping);
        }
        responseObserver.onCompleted();
    }
}

@@ -1187,16 +1187,95 @@
 eList();
+%0A%0A        ApplicationMapping.Builder builder = ApplicationMapping.newBuilder();
 %0A       
@@ -1619,68 +1619,15 @@
     
-ApplicationMapping mapping = ApplicationMapping.newB
+b
 uilder
-()
 .add
@@ -1647,30 +1647,28 @@
 , value)
-.build()
 ;%0A    
+    %7D%0A
         
@@ -1695,27 +1695,25 @@
 ext(
-mapping);%0A        %7D
+builder.build());
 %0A   

add application id into mapping builder which inside of for.