package de.ph87.isabell_und_timo.picture;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.NonNull;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.server.ResponseStatusException;

import java.io.IOException;
import java.util.stream.Collectors;

@Slf4j
@CrossOrigin
@RestController
@RequiredArgsConstructor
@RequestMapping("PictureAdmin")
public class PictureAdminController {

  private final PictureService pictureService;

  private final PictureRepository pictureRepository;

  @NonNull
  @GetMapping("visible")
  public String visible(@NonNull final HttpServletRequest request) {
    verifyLocal(request);
    return pictureRepository
      .findAllDtoByVisibleTrue()
      .stream()
      .map(p -> "<a href='/PictureAdmin/%s/visible/false'><img src='/Picture/%s/preview' loading='lazy' alt='%s' style='width: 100%%;'></a>\n".formatted(p.uuid, p.uuid, p.uuid))
      .collect(Collectors.joining("\n"));
  }

//  @GetMapping("{uuid}/visible/{visible}")
//  public void visible(@PathVariable @NonNull final String uuid, @PathVariable final boolean visible, @NonNull final HttpServletRequest request, @NonNull final HttpServletResponse response) throws IOException {
//    verifyLocal(request);
//    pictureService.visible(uuid, visible);
//    response.sendRedirect(request.get);
//  }

  private static void verifyLocal(final HttpServletRequest request) {
    if (!request.getRemoteAddr().startsWith("10.") && !request.getRemoteAddr().equals("127.0.0.1")) {
      throw new ResponseStatusException(HttpStatus.NOT_FOUND);
    }
  }

}
