package kr.xit.ens.ktgbs.web;

import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;

import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.media.Content;
import io.swagger.v3.oas.annotations.media.ExampleObject;
import io.swagger.v3.oas.annotations.tags.Tag;
import kr.xit.biz.ens.model.kt.KtCommonDTO;
import kr.xit.biz.ens.model.ktgbs.KtGbsDTO;
import kr.xit.biz.ktgbs.service.IBizKtGbsService;
import lombok.RequiredArgsConstructor;

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;

/**
 * <pre>
 * description : KT GBIS 에서 사용 되는 API
 * packageName : kr.xit.ens.ktgbs.web
 * fileName    : KtGbsMmsInboundController
 * author      : limju
 * date        : 2024-08-19
 * ======================================================================
 * 변경일         변경자        변경 내용
 * ----------------------------------------------------------------------
 * 2024-08-19   limju       최초 생성
 *
 * </pre>
 */
@Tag(name = "KtGbsInboundController", description = "KT GIBIS Inbound API - KT GIBIS 에서 사용하는 API")
@RequiredArgsConstructor
@RestController
public class KtGbsInboundController {
    private final IBizKtGbsService bizService;

    /**
     * <pre>
     * 메세지 발송/수신 결과 전송 -> KT GIBIS에서 호출
     * - KT GBIS 에서 호출 되는 서비스
     * - url 고정 : http://{각대행사(IP:Port)}/api/msg/result
     * @param reqDTO KtMsgRsltRequest
     * @return KtCommonResponse
     * </pre>
     */
    @io.swagger.v3.oas.annotations.parameters.RequestBody(required = true, content = {
        @Content(
            mediaType = "application/json",
            examples = {
                @ExampleObject(
                    value = """
                        {
                             "service_cd" : "CD001",
                             "reqs" : [
                                 {
                                     "src_key" : "OvSsuljd1K-67c1fc38-1a59-4fbe-930e-802db6609140",
                                     "mms_sndg_rslt_sqno" : 2,
                                     "prcs_dt" : "20240819",
                                     "mms_bsns_dvcd" : "01001",
                                     "mbl_bzowr_dvcd" : "02",
                                     "rl_mms_sndg_telno" : "4230",
                                     "mms_rslt_dvcd" : "40",
                                     "mms_sndg_tmst" : "20240819090237",
                                     "mms_rcv_tmst" : "20240819090239",
                                     "mms_rdg_tmst" : "20240819114405",
                                     "prev_approve_yn" : "Y",
                                     "msg_type" : "2"
                                 }
                            ]
                        }
                        """
                ),
            })
    })
    @Operation(summary = "메세지 발송/수신 결과 전송 -> KT GIBIS에서 호출", description = "메세지 발송/수신 결과 전송 -> KT GIBIS에서 호출")
    //@PostMapping(value = "/goji/kt/gibis/stat/bulk", produces = MediaType.APPLICATION_JSON_VALUE)
    @PostMapping(value = "/goji/api/msg/result", produces = MediaType.APPLICATION_JSON_VALUE)
    public KtCommonDTO.KtCommonResponse messageResult(@RequestBody final KtGbsDTO.MsgRsltRequest reqDTO) {
        return bizService.messageResult(reqDTO);
    }

    @Operation(summary = "링크이미지 출력")
    @GetMapping(value = "/goji/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());
        }
    }
}
