package kr.co.uplus.ez.api.comm;

import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.util.stream.Stream;

import org.springframework.core.io.Resource;
import org.springframework.core.io.UrlResource;
import org.springframework.stereotype.Service;
import org.springframework.util.FileSystemUtils;
import org.springframework.web.multipart.MultipartFile;

import kr.co.uplus.ez.api.comm.FileService;

@Service
public class FileServiceImpl implements FileService {
	// @Value("${spring.servlet.multipart.location}")
	  private String uploadPath = "/efs/admin";

	  @Override
	  public void init() {
	    try {
	      Files.createDirectories(Paths.get(uploadPath));

	    } catch (IOException e) {
	      throw new RuntimeException("폴더 생성 실패");
	    }
	  }

	  @Override
	  public void store(MultipartFile file) {
	    try {
	      if (file.isEmpty()) {
	        throw new Exception("빈 파일입니다.");
	      }

	      Path root = Paths.get(uploadPath);

	      if (!Files.exists(root)) {
	        init();
	      }

	      try (InputStream inputStream = file.getInputStream()) {
	        Files.copy(inputStream, root.resolve(
	            file.getOriginalFilename()), StandardCopyOption.REPLACE_EXISTING
	        );
	        
	      } catch (Exception e) {
	        throw new RuntimeException("파일을 저장할 수 없습니다. Error: " + e.getMessage());
	      }

	    } catch (Exception e) {
	      throw new RuntimeException("파일을 저장할 수 없습니다. Error: " + e.getMessage());
	    }
	  }

	  @Override
	  public Stream<Path> loadAll() {
	    try {
	      Path root = Paths.get(uploadPath);
	      return Files.walk(root, 1).filter(path -> !path.equals(root));
	      
	    } catch (IOException e) {
	      throw new RuntimeException("파일 읽기 실패", e);
	    }
	  }

	  @Override
	  public Path load(String filename) {
	    return Paths.get(uploadPath).resolve(filename);
	  }

	  @Override
	  public Resource loadAsResource(String filename) {
	    try {
	      Path file = load(filename);
	      Resource resource = new UrlResource(file.toUri());
	      
	      if (resource.exists() || resource.isReadable()) {
	        return resource;

	      } else {
	        throw new RuntimeException("파일을 읽을 수 없습니다. : " + filename);
	      }

	    } catch (MalformedURLException e) {
	      throw new RuntimeException("파일을 읽을 수 없습니다. : " + filename, e);
	    }
	  }

	  @Override
	  public void deleteAll() {
	    FileSystemUtils.deleteRecursively(Paths.get(uploadPath).toFile());
	  }

	  @Override
	  public void deleteFile(String filename) {
	    FileSystemUtils.deleteRecursively(Paths.get(uploadPath + "\\" + filename).toFile());
	  }
}
