package cn.reghao.autodop.dmaster.app.controller;

import cn.reghao.jdkutil.result.WebBody;
import cn.reghao.jdkutil.serializer.JsonConverter;
import cn.reghao.autodop.dmaster.app.model.po.config.AppConfig;
import cn.reghao.autodop.dmaster.util.UploadDownload;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.BufferedInputStream;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.nio.charset.StandardCharsets;

/**
 * @author reghao
 * @date 2019-08-30 18:49:15
 */
@Slf4j
@Api(tags = "应用配置备份接口")
@RestController
@RequestMapping("/api/bak")
public class AppBakController {
    private final UploadDownload uploadDownload;

    public AppBakController(UploadDownload uploadDownload) {
        this.uploadDownload = uploadDownload;
    }

    @ApiOperation(value = "导出 JSON 数据")
    @GetMapping("/config/app/export")
    @ResponseBody
    public void dataBackup(HttpServletResponse response) throws IOException {
        String json = "";
        ByteArrayInputStream bytesIn = new ByteArrayInputStream(json.getBytes());
        BufferedInputStream bis = new BufferedInputStream(bytesIn);
        uploadDownload.download("test", bis, response);
    }

    @ApiOperation(value = "导入 JSON 数据")
    @PostMapping("/config/app/import")
    public String dataRestore(@RequestParam("file") MultipartFile file) throws IOException {
        byte[] bytes = file.getBytes();
        String json = new String(bytes, StandardCharsets.UTF_8);
        AppConfig app = JsonConverter.jsonToObject(json, AppConfig.class);
        return WebBody.success();
    }
}
