package com.icomsys.main_vm.biz.common.common.service;

import com.google.gson.Gson;
import com.icomsys.main_vm.biz.advice.excep.CustomNotFoundException;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.MessageSource;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.InputStreamResource;
import org.springframework.http.*;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.core.io.Resource;

import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.net.InetAddress;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

@Service
@RequiredArgsConstructor
@Slf4j
public class FileService {
    @Value("${Server.port}")
    private String port;
    @Value("${file.path}")
    private String filePath;
    private static String col = ":";
    private final MessageSource messageSource;
    private final HttpServletRequest request;

    public List<String> FileSaveService(MultipartFile[] uploadfile) throws IllegalStateException, IOException {
        List<String> ll = new ArrayList<>();
        String nn = "";
        String[] url = request.getRequestURI().split("/");
        log.info("test14 - {}", new Gson().toJson(url));
        int size = url.length;
        log.info("test14 - {}", size);

        for (MultipartFile mf : uploadfile) {
            if (!mf.isEmpty()) {
                nn = UUID.randomUUID().toString();
                File newFileName = new File(nn + "_" + mf.getOriginalFilename());
                log.info("path - - {}", newFileName.getPath());
                Path directory = Paths.get(filePath + "/" + url[size - 1]).toAbsolutePath().normalize();
                // directory 해당 경로까지 디렉토리를 모두 만든다.
                Files.createDirectories(directory);
                // 파일명을 바르게 수정한다.
                String fileName = StringUtils.cleanPath(nn + "_" + mf.getOriginalFilename()).replaceAll(" ", "");
                // 파일명에 '..' 문자가 들어 있다면 오류를 발생하고 아니라면 진행(해킹및 오류방지)
                Assert.state(!fileName.contains(".."), "Name of file cannot contain '..'");
                // 파일을 저장할 경로를 Path 객체로 받는다.
                Path targetPath = directory.resolve(fileName).normalize();
                // 파일이 이미 존재하는지 확인하여 존재한다면 오류를 발생하고 없다면 저장한다.
                Assert.state(!Files.exists(targetPath), fileName + " File alerdy exists.");
                mf.transferTo(targetPath);
//                ll.add("http://192.168.0.42:9506/admin/img/"+boardName+"/"+fileName);
                ll.add(InetAddress.getLocalHost().getHostAddress() + col + port + "/" + url[size - 1] + "/" + fileName);
                log.info("upload file -{}", new Gson().toJson(ll));
            }
        }
        return ll;
    }

    public ResponseEntity<Resource> imgGetService(String imgPath) throws IOException {
        String basepath = filePath;
//        String basepath = "";
        Resource recorce = new FileSystemResource(basepath + imgPath);
        if (!recorce.exists()) {
            log.info("notfound");
            return new ResponseEntity<Resource>(HttpStatus.NOT_FOUND);
        }
        HttpHeaders header = new HttpHeaders();
        Path filePath = null;
        try {
            filePath = Paths.get(basepath + imgPath);
            header.add("Content-Type", Files.probeContentType(filePath));
        } catch (IOException e) {
            e.printStackTrace();
        }
        return new ResponseEntity<Resource>(recorce, header, HttpStatus.OK);
    }


    public ResponseEntity<Resource> PdfDownload(String name) throws IOException, CustomNotFoundException {
        ClassPathResource cpr = new ClassPathResource("/document/"+name);
        InputStreamResource r =  new InputStreamResource(cpr.getInputStream());
        ContentDisposition cd = ContentDisposition.builder("inline")
                .filename(name)
                .name(name)
                .build();
        HttpHeaders haHttpHeaders = new HttpHeaders();
        haHttpHeaders.setContentDisposition(cd);
        return ResponseEntity.ok()
//                .contentType(MediaType.APPLICATION_OCTET_STREAM)
                .contentType(MediaType.valueOf(MediaType.APPLICATION_PDF_VALUE))
                .cacheControl(CacheControl.noCache())
                .headers(haHttpHeaders)
                .body(r);
    }


}







