package com.mx.cneeds.server.datashow.web.device;

import com.mx.cneeds.common.constant.FilePath;
import com.mx.hbasefile.hadoop.hdfs.api.HdfsTemplate;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;

/**
 * @ClassName DeviceFileController
 * @Author zzrdark
 * @Date 2020-07-28 19:27
 * @Description TODO
 **/
@Controller
@Slf4j
@RequestMapping("/deviceFile/")
public class DeviceFileController {

    @Autowired
    private HdfsTemplate hdfsTemplate;

    @RequestMapping("/deviceFileDownload/{fileSize}/{fileName}")
    public void download(@PathVariable("fileName") String fileName, @PathVariable("fileSize") String fileSize,
                         HttpServletResponse response) throws IOException {
        StringBuffer dirPath = new StringBuffer(FilePath.deviceInfoExportFilePath);
        InputStream inputStream = hdfsTemplate.openFile(dirPath.toString(), fileName);

        ServletOutputStream outputStream = response.getOutputStream();
        String mediaType = fileName.substring(fileName.indexOf("."));
        response.setContentType(mediaType);
        response.addHeader("Content-Disposition", "attachment; filename" + "testfilename");


        byte[] bytes = new byte[1024];

        long total = Long.valueOf(fileSize);
        while (total>0) {
            inputStream.read(bytes);
            outputStream.write(bytes,0, total>1024?1024: (int) total);
            outputStream.flush();
            total-=1024;
        }
        outputStream.close();
    }
}
