package cn.reghao.tnb.oss.store.config;

import cn.reghao.jutil.jdk.thread.ThreadPoolWrapper;
import cn.reghao.tnb.oss.api.dto.StoreNodeDto;
import cn.reghao.tnb.oss.api.dto.disk.DiskVolume;
import cn.reghao.tnb.oss.api.iface.StoreService;
import cn.reghao.tnb.oss.store.config.props.SpringProperties;
import cn.reghao.tnb.oss.store.service.ConsoleServiceWrapper;
import cn.reghao.tnb.oss.store.tomcat.TomcatStarter;
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.concurrent.ExecutorService;

/**
 * @author reghao
 * @date 2022-03-23 09:22:01
 */
@Slf4j
@Component
public class SpringLifecycle implements ApplicationRunner, DisposableBean {
    private final SpringProperties springProperties;
    private final StoreService storeService;
    private final ConsoleServiceWrapper consoleServiceWrapper;
    private final ExecutorService threadPool;
    private final TomcatStarter tomcatStarter;

    public SpringLifecycle(SpringProperties springProperties, StoreService storeService,
                           ConsoleServiceWrapper consoleServiceWrapper, TomcatStarter tomcatStarter) {
        this.springProperties = springProperties;
        this.storeService = storeService;
        this.consoleServiceWrapper = consoleServiceWrapper;
        this.threadPool = ThreadPoolWrapper.threadPool("tomcat");
        this.tomcatStarter = tomcatStarter;
    }

    @Override
    public void run(ApplicationArguments args) {
        //threadPool.submit(tomcatStarter);
        registerStoreNode();
    }

    private void registerStoreNode() {
        // 注册 oss-store 到 oss-console
        String nodeAddr = springProperties.getNodeAddress();
        int httpPort = springProperties.getHttpPort();
        int rpcPort = springProperties.getRpcPort();
        List<DiskVolume> diskVolumeList = storeService.getDiskVolumes();
        StoreNodeDto storeNodeDto = new StoreNodeDto(nodeAddr, httpPort, rpcPort, diskVolumeList);
        consoleServiceWrapper.registerNode(storeNodeDto);
        log.info("StoreNode 已注册到 oss-console...");
    }

    @Override
    public void destroy() {
    }
}
