package com.remy.graphql.resolvers.dataloader;

import com.remy.common.module.GoodsDTO;
import com.remy.common.module.OrderDTO;
import com.remy.common.module.UserDTO;
import graphql.kickstart.execution.context.GraphQLContext;
import graphql.kickstart.tools.GraphQLResolver;
import graphql.schema.DataFetchingEnvironment;
import org.dataloader.DataLoader;
import org.dataloader.DataLoaderRegistry;
import org.springframework.stereotype.Component;

import java.util.concurrent.CompletableFuture;

@Component
public class OrderDataLoaderResolver implements GraphQLResolver<OrderDTO> {

    public CompletableFuture<GoodsDTO> goods(OrderDTO orderDTO, DataFetchingEnvironment env){
        DataLoaderRegistry registry = ((GraphQLContext) env.getContext()).getDataLoaderRegistry();
        DataLoader<String, GoodsDTO> goodsDataLoader = registry.getDataLoader("goodsDataLoader");
        if (goodsDataLoader != null) {
            return goodsDataLoader.load(orderDTO.getGoodsSerialNo());
        }
        throw new IllegalStateException("No goods data loader found");
    }

    public CompletableFuture<UserDTO> user(OrderDTO orderDTO, DataFetchingEnvironment env){
        DataLoaderRegistry registry = ((GraphQLContext) env.getContext()).getDataLoaderRegistry();
        DataLoader<Long, UserDTO> userDataLoader = registry.getDataLoader("userDataLoader");
        if (userDataLoader != null) {
            return userDataLoader.load(orderDTO.getUserID());
        }
        throw new IllegalStateException("No user data loader found");
    }
}
