package cokr.xit.ens.modules.common.ctgy.sys.util.presentation;

import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;

@Tag(name = "LinkImgController")
@Slf4j
@Controller
public class LinkImgController {
    @Operation(summary = "링크이미지 출력")
    @GetMapping(value = "/sys/util/lnk/img")
    public void printImg(HttpServletRequest request, HttpServletResponse response, @RequestParam String link, @RequestParam String type) throws IOException {

        String mime = null;
        if ("jpg".equals(type) || "jpeg".equals(type))
            mime = "image/jpeg";
        else if ("png".equals(type))
            mime = "image/png";
        else if ("gif".equals(type))
            mime = "image/gif";
        else
            mime = "image/jpeg";


        try (InputStream inputStream = new URL(link).openStream();
             ServletOutputStream outputStream = response.getOutputStream();) {

            response.setHeader("Cache-Control", "no-store");
            response.setHeader("Pragma", "no-cache");
            response.setDateHeader("Expires", 0);
            response.setContentType(mime);


            int length;
            byte[] buffer = new byte[1024];
            while ((length = inputStream.read(buffer)) != -1) {
                outputStream.write(buffer, 0, length);
            }


            outputStream.flush();

        } catch (FileNotFoundException e) {
            response.getWriter().println("File is Not Found." + e.getMessage());
        } catch (IOException e) {
            response.getWriter().println("I/O Error Occurred!!. " + e.getMessage());
        }
    }
}
