package cn.reghao.oss.store.config;

import cn.reghao.jutil.jdk.serializer.JsonConverter;
import cn.reghao.oss.sdk.OssConsoleClient;
import cn.reghao.oss.storeapi.dto.ObjectChannel;
import cn.reghao.oss.storeapi.dto.StoreDiskDto;
import cn.reghao.oss.storeapi.dto.StoreNodeDto;
import cn.reghao.oss.storeapi.dto.StoreProperties;
import cn.reghao.oss.store.config.props.SpringProperties;
import cn.reghao.oss.store.service.FileStoreService;
import cn.reghao.oss.store.service.StoreLocalService;
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;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @author reghao
 * @date 2022-03-23 09:22:01
 */
@Slf4j
@Component
public class SpringLifecycle implements ApplicationRunner, DisposableBean {
    private final SpringProperties springProperties;
    private final FileStoreService fileStoreService;
    private final OssConsoleClient ossConsoleClient;
    private final StoreLocalService storeLocalService;

    public SpringLifecycle(SpringProperties springProperties, FileStoreService fileStoreService,
                           OssConsoleClient ossConsoleClient, StoreLocalService storeLocalService) {
        this.springProperties = springProperties;
        this.fileStoreService = fileStoreService;
        this.ossConsoleClient = ossConsoleClient;
        this.storeLocalService = storeLocalService;
    }

    @Override
    public void run(ApplicationArguments args) throws Exception {
        initStoreNode();
        log.info("执行文件任务...");
        log.info("文件任务执行完成...");
    }

    private void initStoreNode() throws Exception {
        log.info("初始化 StoreNode...");

        // 注册 oss-store 到 oss-console
        String nodeAddr = springProperties.getNodeAddress();
        int httpPort = springProperties.getHttpPort();
        int rpcPort = springProperties.getRpcPort();
        List<StoreDiskDto> list = fileStoreService.getStoreDisks().stream()
                .map(StoreDiskDto::new)
                .collect(Collectors.toList());
        StoreNodeDto storeNodeDto = new StoreNodeDto(nodeAddr, httpPort, rpcPort, list);
        String jsonPayload = JsonConverter.objectToJson(storeNodeDto);
        //ossConsoleClient.registerNode(jsonPayload);

        // 获取 oss-store 配置和默认 channel
        StoreProperties storeProperties = ossConsoleClient.getStoreProperties(nodeAddr);
        List<ObjectChannel> objectChannels = ossConsoleClient.getObjectChannels(nodeAddr);
        storeLocalService.initChannels(storeProperties, objectChannels);
        log.info("StoreNode 初始化完成...");
    }

    @Override
    public void destroy() {
    }
}
