package com.eactive.eai.rms.onl.apim.file;

import com.eactive.apim.portal.file.entity.FileDetail;
import com.eactive.apim.portal.file.service.FileService;
import org.apache.commons.io.IOUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;

@Controller
@RequestMapping("/file")
public class AdminFileDownloadController {

    FileService fileService;

    public AdminFileDownloadController(FileService fileService) {
        this.fileService = fileService;
    }

    @GetMapping(value = "/download.do")
    public void downloadFileAdmin(@RequestParam(value = "fileId", defaultValue = "0") String fileId,
                                  @RequestParam(value = "fileSn", defaultValue = "-1") int fileSn,
                                  HttpServletResponse response) throws IOException {

        // Get the FileDetail object from the service layer
        FileDetail fileDetail = fileService.getFileDetailByIds(fileId, fileSn);

        // Set the response headers
        response.setContentType("application/octet-stream");
        String encodedFilename = URLEncoder.encode(fileDetail.getOriginalFileName() + "." + fileDetail.getFileExtension(), "UTF-8");
        response.setHeader("Content-Disposition", "attachment; filename=\"" + encodedFilename + "\";");
        response.setContentLength(fileDetail.getFileSize());

        // Decode the base64-encoded file contents and write the file to the response stream
        byte[] fileContents = fileService.retrieveFileContent(fileDetail);
        IOUtils.write(fileContents, response.getOutputStream());
        response.flushBuffer();
    }
}
