
package cn.orionsec.ops.controller;

import cn.orionsec.kit.lang.exception.NotFoundException;
import cn.orionsec.kit.web.servlet.web.Servlets;
import cn.orionsec.ops.annotation.IgnoreAuth;
import cn.orionsec.ops.annotation.IgnoreWrapper;
import cn.orionsec.ops.annotation.RestWrapper;
import cn.orionsec.ops.constant.Const;
import cn.orionsec.ops.constant.download.FileDownloadType;
import cn.orionsec.ops.entity.request.file.FileDownloadRequest;
import cn.orionsec.ops.service.api.FileDownloadService;
import cn.orionsec.ops.utils.Valid;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Api(tags = "文件下载")
@RestController
@RestWrapper
@RequestMapping("/orion/api/file-download")
public class FileDownloadController {

    @Resource
    private FileDownloadService fileDownloadService;

    @PostMapping("/token")
    @ApiOperation(value = "检查并获取下载文件token")
    public String getDownloadToken(@RequestBody FileDownloadRequest request) {
        Long id = Valid.notNull(request.getId());
        FileDownloadType type = Valid.notNull(FileDownloadType.of(request.getType()));
        return fileDownloadService.getDownloadToken(id, type);
    }

    @IgnoreWrapper
    @IgnoreAuth
    @GetMapping("/{token}/exec")
    @ApiOperation(value = "下载文件")
    public void downloadLogFile(@PathVariable String token, HttpServletResponse response) throws IOException {
        try {
            fileDownloadService.execDownload(token, response);
        } catch (NotFoundException e) {
            // 文件未找到
            Servlets.transfer(response, Const.EMPTY.getBytes(), Const.UNKNOWN);
        }
    }

}
