package com.alterdekim.game.controller;

import com.alterdekim.game.storage.FileSystemStorageService;
import com.alterdekim.game.storage.StorageFileNotFoundException;
import com.alterdekim.game.storage.StorageProperties;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.nio.file.Files;
import java.nio.file.Path;

@Slf4j
@RestController
@EnableConfigurationProperties(StorageProperties.class)
public class FileServerController {

    @Autowired
    private FileSystemStorageService storageService;

    public static final String URL_PATH = "file";

    @RequestMapping(value = "/"+URL_PATH+"/**", method = RequestMethod.GET)
    @ResponseBody
    public ResponseEntity<byte[]> serveFile(HttpServletRequest request) {
        try {
            String filename = request.getRequestURI().substring(6);
            Path path = storageService.load(filename);
            return ResponseEntity.ok().contentType(switch(filename.substring(0, 3)) {
                case "swf", "pub" -> MediaType.parseMediaType("application/x-shockwave-flash");
                case "css" -> MediaType.parseMediaType("text/css");
                case "_js" -> MediaType.parseMediaType("text/javascript");
                case "img" -> MediaType.parseMediaType("image/jpeg");
                case "svg" -> MediaType.parseMediaType("image/svg+xml");
                default -> MediaType.TEXT_PLAIN;
            }).body(Files.readAllBytes(path));
        } catch (Exception e) {
            log.error(e.getMessage());
        }
        return ResponseEntity.notFound().build();
    }

    @ExceptionHandler(StorageFileNotFoundException.class)
    public ResponseEntity<?> handleStorageFileNotFound(StorageFileNotFoundException exc) {
        return ResponseEntity.notFound().build();
    }
}

