package cn.reghao.bnt.web.devops.app.service.bd.impl;

import cn.reghao.bnt.common.msg.constant.PackType;
import cn.reghao.bnt.web.devops.app.db.query.AppBuildQuery;
import cn.reghao.bnt.web.devops.app.model.po.config.AppConfig;
import cn.reghao.bnt.web.devops.app.model.po.log.BuildLog;
import cn.reghao.bnt.web.devops.app.service.bd.GetApp;
import cn.reghao.bnt.web.devops.builder.model.LocalBuildDir;
import cn.reghao.bnt.web.util.UploadDownload;
import cn.reghao.jutil.web.ServletUtil;
import org.springframework.stereotype.Service;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;

/**
 * @author reghao
 * @date 2023-02-24 21:17:58
 */
@Service
public class GetAppImpl implements GetApp {
    private final AppBuildQuery appBuildQuery;
    private final UploadDownload uploadDownload;

    public GetAppImpl(AppBuildQuery appBuildQuery, UploadDownload uploadDownload) {
        this.appBuildQuery = appBuildQuery;
        this.uploadDownload = uploadDownload;
    }

    @Override
    public String packageUrl(String buildLogId) throws Exception {
        BuildLog buildLog = appBuildQuery.getBuildLog(buildLogId);
        if (buildLog == null) {
            String errMsg = "构建不存在";
            throw new Exception(errMsg);
        }

        String appId = buildLog.getAppConfig().getAppId();
        AppConfig appConfig = appBuildQuery.getAppConfig(appId);
        if (appConfig == null) {
            String errMsg = "应用不存在";
            throw new Exception(errMsg);
        }

        String packagePath = buildLog.getPackagePath();
        String packType = appConfig.getPackerConfig().getType();
        switch (PackType.valueOf(packType)) {
            case zip:
                return packagePath;
            case docker:
                String errMsg = "docker 打包类型的应用不能下载";
                throw new Exception(errMsg);
            default:
                throw new Exception(String.format("打包类型 %s 不存在", packType));
        }
    }

    @Override
    public void dlPackage(String filename) throws Exception {
        String[] arr = filename.split("_");
        if (arr.length != 2) {
            String errMsg = String.format("%s 不合法", filename);
            throw new Exception(errMsg);
        }

        String appId = arr[0];
        String commitId = arr[1];
        String filePath = LocalBuildDir.packDir + File.separator + appId + File.separator + filename;
        File file = new File(filePath);
        if (!file.exists()) {
            throw new Exception("文件不存在");
        }

        FileInputStream fileInputStream = new FileInputStream(file);
        BufferedInputStream bis = new BufferedInputStream(fileInputStream);
        uploadDownload.download(filename, bis, ServletUtil.getResponse());
    }
}
