package io.delphiplatform.api.v3.view;

import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.server.ResponseStatusException;

import java.util.List;
import java.util.concurrent.CompletableFuture;

import javax.transaction.NotSupportedException;

import io.delphiplatform.api.v3.bigtable.BigtablePopularityService;
import io.delphiplatform.api.v3.model.Popularities;
import io.delphiplatform.api.v3.model.Popularity;
import io.delphiplatform.api.v3.view.util.Params;
import lombok.extern.slf4j.Slf4j;

@Slf4j
@Controller
@RequestMapping("${spring.data.rest.base-path:/v3}")
public class PopularityApiController implements PopularityApi {

    private final BigtablePopularityService popularityService;

    public PopularityApiController(BigtablePopularityService popularityService) {
        this.popularityService = popularityService;
    }

    @Override
    public CompletableFuture<ResponseEntity<Popularities>> getSearchData(Params params) {
        try {
            CompletableFuture<List<Popularity>> models = popularityService
                .getPopularityModels(params);
            return models.thenApply(r -> ResponseEntity.ok(new Popularities()
                .items(r)
                .nextCursor(params.getNextCursor())
                .count(r.size())));
        } catch (NotSupportedException e) {
            log.error("Error while getting popularities.", e);
            throw new ResponseStatusException(HttpStatus.NOT_IMPLEMENTED, e.getMessage());
        }
    }

}
