package com.ningdatech.carapi.log.manage;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Objects;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.client.RestTemplate;

import com.ningdatech.carapi.log.constant.LogBackupConstant;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;

/**
 * @author CMM
 * @since 2023/01/06 16:40
 */
@Component
@RequiredArgsConstructor
@Slf4j
public class LogManage {

    private final RestTemplate restTemplate;

    @Value("${log.backup.url}")
    private String backupUrl;

    public String backupLog() {

        ResponseEntity<byte[]> entity = restTemplate.getForEntity(backupUrl, byte[].class);
        if (Boolean.TRUE.equals(saveFile(entity, LogBackupConstant.LOG_FILE_PATH))) {
            return "备份成功";
        }else {
            return "备份失败";
        }
    }

    private Boolean saveFile(ResponseEntity<byte[]> entity, String backupFilePath) {
        byte[] body = entity.getBody();
        try {
            if (Objects.nonNull(body)) {
                File directory = new File("");
                // 临时文件存储路径
                String filePath = directory.getAbsolutePath() + File.separator + backupFilePath;
                File saveDir = new File(filePath);
                if (!saveDir.exists()) {
                    saveDir.mkdirs();
                }
                File saveFile = new File(saveDir, LogBackupConstant.LOG_FILE_NAME);
                FileOutputStream fos = new FileOutputStream(saveFile);
                FileCopyUtils.copy(body, fos);
                fos.flush();
                fos.close();
                return true;
            }
        } catch (IOException e) {
            log.error("文件保存失败：" + e.getMessage());
            return false;
        }
        return false;
    }
}
