package io.delphiplatform.api.v3.view;

import org.springframework.beans.factory.annotation.Autowired;
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.util.OffsetBasedPageRequest;
import io.delphiplatform.api.v3.bigtable.BigtableChartmetricService;
import io.delphiplatform.api.v3.model.ArtistFollower;
import io.delphiplatform.api.v3.model.ArtistFollowers;
import io.delphiplatform.api.v3.model.ArtistSimple;
import io.delphiplatform.api.v3.model.Artists;
import io.delphiplatform.api.v3.model.SortOrder;
import io.delphiplatform.api.v3.rdb.service.ArtistService;
import io.delphiplatform.api.v3.view.util.Params;

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

    private final BigtableChartmetricService bigtableChartmetricService;
    private final ArtistService artistService;

    @Autowired
    public ArtistsApiController(BigtableChartmetricService bigtableChartmetricService,
        ArtistService artistService) {
        this.bigtableChartmetricService = bigtableChartmetricService;
        this.artistService = artistService;
    }

    @Override
    public ResponseEntity<ArtistSimple> findOne(String artistId) {
        return ResponseEntity.ok(artistService.findOne(artistId));
    }

    @Override
    public CompletableFuture<ResponseEntity<ArtistFollowers>> getArtistFollowers(Params params) {
        try {
            CompletableFuture<List<ArtistFollower>> models = bigtableChartmetricService.getModels(params);
            return models.thenApply(r -> ResponseEntity.ok(new ArtistFollowers()
                .items(r)
                .nextCursor(params.getNextCursor())
                .count(r.size())));
        } catch (NotSupportedException e) {
            throw new ResponseStatusException(HttpStatus.NOT_IMPLEMENTED, e.getMessage());
        }
    }

    @Override
    public ResponseEntity<Artists> getSearchData(String productId, String trackId, String isrc, List<String> artistIds,
        Integer limit, Integer offset, String sortBy, SortOrder sortOrder) {
        List<ArtistSimple> artists = artistService.find(productId, trackId, isrc, artistIds,
            OffsetBasedPageRequest.ofParamsToCamelCase(offset, limit, sortOrder, sortBy));
        return ResponseEntity.ok(new Artists().items(artists).count(artists.size()));
    }

}
