package GRPCConnection.GRPCServer;

import io.grpc.stub.StreamObserver;
import org.AutoHealerAndClusterSearch.AutoHealerAndClusterSearch.Coordinator;
import org.AutoHealerAndClusterSearch.SearchReply;
import org.AutoHealerAndClusterSearch.SearchRequest;
import org.AutoHealerAndClusterSearch.SearchServiceGrpc;
import org.apache.zookeeper.KeeperException;
import org.lognet.springboot.grpc.GRpcService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


import java.util.ArrayList;
import java.util.List;


/**
 * the server of GRPC is the coordinator
 * it has threads embedded , we must configure the Coordinator only yo
 * handle requests sent from here , no need to act like a Server !!
 * */
@GRpcService
public class GRPCServer extends SearchServiceGrpc.SearchServiceImplBase
{
    private Coordinator coordinator;
   /* public GRPCServer(Coordinator coordinator)
    {
        this.coordinator = coordinator;
    }*/
    //Logger logger = LoggerFactory.getLogger(GRPCServer.class);

    @Override
    public void search(SearchRequest request, StreamObserver<SearchReply> responseObserver)
    {

        //logger.info("Request Has Arrived , Query is :" + request.getQuery());

        List<String> ans = new ArrayList<>();

        String x = request.getQuery();
        ans.add("Sorry Something Went Wrong " + x);

        /*try
        {
            ans = coordinator.search(request.getQuery());
        }
        catch (IOException | InterruptedException | KeeperException | ExecutionException e)
        {
            logger.error("Error In GRPC While Getting answers for Query");
            //throw new RuntimeException(e);
        }*/
        SearchReply reply = SearchReply.newBuilder().addAllFiles(ans).build();

        responseObserver.onNext(reply);

        responseObserver.onCompleted();
    }
}
