package com.icomsys.main_vm.biz.rcp.learningTest;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

import javax.servlet.ServletContext;
import javax.servlet.http.Part;

@Slf4j
public class UploadUtil {

    //@Value("${file.uploadpath}")
    private String uploadPath;
    private ServletContext app;

    /* 생성 메서드 */
    public static UploadUtil create(ServletContext app) {
        UploadUtil uploadUtil = new UploadUtil();
        uploadUtil.setApp(app);
        uploadUtil.setUploadPath("/logs/was/aicb/cinnamon_ui/files/stttest/");

        return uploadUtil;
    }

    private void setApp(ServletContext app) {
        this.app = app;
    }
    private void setUploadPath(String realPath) {
        this.uploadPath = realPath;
    }

    /* 파일 저장 */
    public void saveFiles(Part filePart, String folderPath) {

        String realPath = uploadPath + File.separator + folderPath;
        String filePath = realPath + File.separator + filePart.getSubmittedFileName();
        log.info("realPath : " + realPath);
        try(
                InputStream fis = filePart.getInputStream();
                OutputStream fos = new FileOutputStream(filePath);)
        {
            byte[] buf = new byte[1024];
            int len = 0;

            while((len = fis.read(buf, 0, 1024)) != -1)
                fos.write(buf, 0, len);

        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    /*/upload 하위 폴더 경로 생성 */
    public String createFilePath() {
        LocalDateTime date = LocalDateTime.now();

        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMdd");

        createFolders(formatter.format(date));

        return formatter.format(date);
    }

    private void createFolders(String paths) {

        File folders = new File(uploadPath, paths);

        if(!folders.exists())
            folders.mkdirs();
    }
}