package cn.reghao.tnb.file.app.config;

import cn.reghao.tnb.file.app.service.AliyunOss;
import cn.reghao.tnb.file.app.service.AliyunService;
import cn.reghao.tnb.file.app.db.mapper.StoreConfigMapper;
import cn.reghao.tnb.file.app.model.constant.OssType;
import cn.reghao.tnb.file.app.model.po.StoreConfig;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;

/**
 * @author reghao
 * @date 2022-03-23 09:22:01
 */
@Slf4j
@Component
public class SpringLifecycle implements ApplicationRunner, DisposableBean {
    private final AppProperties appProperties;
    private final StoreConfigMapper storeConfigMapper;
    private final OssConsoleClientFactory ossConsoleClientFactory;
    private final AliyunOss aliyunOss;
    private final AliyunService aliyunService;

    public SpringLifecycle(AppProperties appProperties, StoreConfigMapper storeConfigMapper,
                           OssConsoleClientFactory ossConsoleClientFactory, AliyunOss aliyunOss,
                           AliyunService aliyunService) {
        this.appProperties = appProperties;
        this.storeConfigMapper = storeConfigMapper;
        this.ossConsoleClientFactory = ossConsoleClientFactory;
        this.aliyunOss = aliyunOss;
        this.aliyunService = aliyunService;
    }

    @Override
    public void run(ApplicationArguments args) throws Exception {
        int ossType = appProperties.getOssType();
        StoreConfig storeConfig = storeConfigMapper.findByOssType(ossType);
        if (ossType == OssType.localOss.getCode()) {
            ossConsoleClientFactory.init(storeConfig);
        } else if (ossType == OssType.aliyunOss.getCode()) {
            aliyunOss.init(storeConfig);
        } else {
            StoreConfig storeConfig1 = storeConfigMapper.findByOssType(OssType.aliyunOss.getCode());
            aliyunOss.init(storeConfig1);
            aliyunService.init(aliyunOss, storeConfig);
        }
        log.info("FileService 启动...");
    }

    @Override
    public void destroy() {
        log.info("FileService 停止...");
    }
}
