package ovh.herisson.Clyde.Services;

import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import ovh.herisson.Clyde.Repositories.FileRepository;
import ovh.herisson.Clyde.Tables.*;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.util.Objects;
import java.util.UUID;

@Service
public class StorageService {


    private final Path rootLocation = Paths.get("cdn/");
    private final FileRepository fileRepo;

    public StorageService(FileRepository filerepo){
        this.fileRepo = filerepo;

		if(!Files.exists(rootLocation)){
			try {
				Files.createDirectories(rootLocation);
			} catch(IOException e){
				e.printStackTrace();
			}
		}
    }


    public StorageFile store(MultipartFile file, FileType fileType) {

        if (file == null || file.getOriginalFilename() == null)
            return null;

        if (file.getOriginalFilename().isEmpty()){return null;}

        UUID uuid = UUID.randomUUID();
        String stringUuid = uuid + "." + file.getOriginalFilename().split("\\.",2)[1];
        try {
            if (file.isEmpty()) {
                return null;
            }

            Path destinationFile = this.rootLocation.resolve(Paths.get(stringUuid));

            Files.copy(file.getInputStream(), destinationFile,StandardCopyOption.REPLACE_EXISTING);
        }
        catch (IOException e) {
            return null;
        }

        String url = this.rootLocation.resolve(Paths.get(Objects.requireNonNull(stringUuid)))
                .normalize().toString();

        return fileRepo.save(new StorageFile(file.getName(),url, fileType));
    }

    public void delete(StorageFile file) throws SecurityException {
        File f = new File(file.getUrl());
        f.delete();

        //Delete l'entité
        fileRepo.delete(file);
    }
}
