package cn.edu.zjvtit.cloudstorage.dataservice.controller;


import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
import result.Result;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.nio.file.Files;

@RestController
public class ObjectsController {
    @Autowired
    Logger logger;
    @PutMapping("/objects/{filename}")
    public String putObject(HttpServletRequest request, @PathVariable("filename") String filename) throws IOException {
        // 存储文件
        logger.info("received put object request");
        File fileToSave = new File("./uploads/" + filename);
        InputStream is  =request.getInputStream();
        FileOutputStream os = new FileOutputStream(fileToSave);
        byte[] buff = new byte[1024];
        int i = 0;
        while ((i = is.read(buff)) != -1) {
            os.write(buff, 0, i);
            os.flush();
        }
        os.close();
        return (new Result( "success","10000")).toString();
    }


    @GetMapping("/objects/{filename}")
    public String getObject(HttpServletResponse response, @PathVariable("filename") String filename) {
        // 读取文件
        File file = new File("./uploads/"+ filename);
        if(!file.exists()){
            return new Result("file not exists","10001").toString();
        }
        response.reset();
        response.setContentType("application/octet-stream");
        response.setCharacterEncoding("utf-8");
        response.setContentLength((int) file.length());
        response.setHeader("Content-Disposition", "attachment;filename=" + filename );

        try(BufferedInputStream bis = new BufferedInputStream(Files.newInputStream(file.toPath()))) {
            byte[] buff = new byte[1024];
            OutputStream os  = response.getOutputStream();
            int i = 0;
            while ((i = bis.read(buff)) != -1) {
                os.write(buff, 0, i);
                os.flush();
            }
            os.close();
        } catch (IOException e) {
            return new Result("file not exists","10001").toString();
        }
        return "";
    }

}
