package com.pack.modeler.service;

import com.pack.modeler.manager.FileStorageManager;
import com.pack.modeler.model.SessionData;
import com.pack.modeler.repository.SessionDataRepo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.sql.Timestamp;
import java.util.UUID;


@Service
public class UploadService {

    @Autowired
    SessionDataRepo sessionDataRepo;

    public String saveFile(MultipartFile file) {
        Timestamp timestamp = new Timestamp(System.currentTimeMillis());
        String pathStr = FileStorageManager.getInstance().getStoragePath() + timestamp.getTime() + "_" + file.getOriginalFilename();

        byte [] bufferedbytes= new byte[1024];
        File f = new File(pathStr);
        FileOutputStream outStream = null;

        int count;
        try {
            BufferedInputStream fileInputStream = new BufferedInputStream(file.getInputStream());
            outStream = new FileOutputStream(f);
            while((count = fileInputStream.read(bufferedbytes)) != -1) {
                outStream.write(bufferedbytes, 0, count);

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

        String token = UUID.randomUUID().toString().toUpperCase() + timestamp.getTime();
        sessionDataRepo.save(SessionData.of(token, pathStr));

        return token;
    }


}
