package com.rdkr.tide_display.backend.images.controller;

import com.rdkr.tide_display.backend.images.domain.ImageFormat;
import com.rdkr.tide_display.backend.images.services.ImageConverterService;
import com.rdkr.tide_display.backend.images.services.MapService;
import java.io.IOException;
import java.util.List;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import lombok.val;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/map")
@RequiredArgsConstructor
@Slf4j
public class MapController {

  private final MapService mapService;
  private final ImageConverterService converterService;

  @GetMapping
  public ResponseEntity<?> getMap(
      @RequestParam(required = false, defaultValue = "GoogleMaps") String mapProvider,
      @RequestParam(required = false, defaultValue = "53.541962") double latitude,
      @RequestParam(required = false, defaultValue = "9.993402") double longitude,
      @RequestParam(required = false, defaultValue = "15") int zoom,
      @RequestParam(required = false, defaultValue = "BINARY") ImageFormat format)
      throws IOException {
    val map = mapService.getStaticMap(mapProvider, latitude, longitude, zoom);
    var result = converterService.convert(map);
    val response = ResponseEntity.ok();
    if (ImageFormat.PNG.equals(format)) {
      return response.contentType(MediaType.IMAGE_PNG).body(result);
    } else {
      val body = converterService.ePaperFormat(result);
      return response.contentType(MediaType.APPLICATION_JSON).body(body);
    }
  }

  @GetMapping("/providers")
  public ResponseEntity<List<String>> getMapProviders() {
    return ResponseEntity.ok(mapService.getMapProviders());
  }
}
