package com.dbnt.sims.config;

import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;

@Service
@RequiredArgsConstructor
public class BaseService {

  @Value("${spring.servlet.multipart.location}")
  protected String locationPath;

  protected String calculationSize(double fileSize){
    String[] units = {"bytes", "KB", "MB", "GB", "TB", "PB"};
    double unitSelector = Math.floor(Math.log(fileSize)/Math.log(1024));
    if(fileSize>0){
      return Math.round((fileSize/Math.pow(1024, unitSelector))*100)/100d+" "+units[(int)unitSelector];
    }else{
      return "";
    }
  }

  public void deleteStoredFile(File deleteFile){
    deleteFile.delete();
  }

  public void saveFile(MultipartFile file, File saveFile){
    if(file.getSize()!=0){ // 저장될 파일 확인
      if(!saveFile.exists()){ // 저장될 경로 확인
        if(saveFile.getParentFile().mkdirs()){
          try{
            saveFile.createNewFile();
          }catch (IOException e){
            e.printStackTrace();
          }
        }
      }
      try {
        file.transferTo(saveFile);
      }catch (IllegalStateException | IOException e){
        e.printStackTrace();
      }
    }
  }
}
