package cn.reghao.oss.store.config;

import cn.reghao.oss.store.config.props.DubboProperties;
import cn.reghao.oss.api.dto.StoreDiskDto;
import cn.reghao.oss.api.dto.StoreNodeDto;
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 StoreLocalService storeLocalService;

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

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

    private void initStoreNode() throws Exception {
        // 注册 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);
        storeLocalService.register(storeNodeDto);
        log.info("StoreNode 已注册到 oss-console...");
    }

    @Override
    public void destroy() {
    }
}
