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

import cn.reghao.jutil.jdk.machine.id.MachineIdLinux;
import cn.reghao.jutil.jdk.result.WebResult;
import cn.reghao.jutil.jdk.serializer.JsonConverter;
import cn.reghao.jutil.jdk.store.LocalStores;
import cn.reghao.jutil.jdk.store.SubDirCount;
import cn.reghao.oss.store.config.SpringProperties;
import cn.reghao.oss.store.db.mapper.DataBlockMapper;
import cn.reghao.oss.store.task.FileTask;
import com.google.gson.reflect.TypeToken;
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.io.File;
import java.io.IOException;
import java.lang.reflect.Type;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author reghao
 * @date 2022-03-23 09:22:01
 */
@Slf4j
@Component
public class AppLifecycle implements ApplicationRunner, DisposableBean {
    private final DataBlockMapper dataBlockMapper;
    private final FileTask fileTask;
    private final SpringProperties springProperties;

    public AppLifecycle(DataBlockMapper dataBlockMapper, FileTask fileTask, SpringProperties springProperties) {
        this.dataBlockMapper = dataBlockMapper;
        this.fileTask = fileTask;
        this.springProperties = springProperties;
    }

    @Override
    public void run(ApplicationArguments args) throws Exception {
        register();
        initLocalStore();

        log.info("执行文件任务...");
        fileTask.exec();
        log.info("文件任务执行完成...");
    }

    private void initLocalStore() throws IOException {
        log.info("初始化本地磁盘...");
        List<String> diskDirs = springProperties.getDiskDirs();
        for (String diskDir : diskDirs) {
            File dir = new File(diskDir);
            if (!dir.exists()) {
                dir.mkdirs();
            }
        }
        LocalStores.init(diskDirs);

        for (String diskDir : diskDirs) {
            List<SubDirCount> list = dataBlockMapper.findSubDirCount("");
            Map<String, Integer> map = new HashMap<>();
            list.forEach(subDirCount -> {
                String relativeDir = subDirCount.getRelativeDir();
                String storeDir = diskDir + relativeDir;
                File file = new File(storeDir);

                int total = subDirCount.getTotal();
                map.put(file.getAbsolutePath(), total);
            });

            LocalStores.initStoreDirs(diskDir, map);
        }
        log.info("本地磁盘数据初始化完成...");
    }

    private void register() throws Exception {
        Map<String, String> map = new HashMap<>();
        map.put("ipv4Addr", new MachineIdLinux().ipv4());
        map.put("httpPort", springProperties.getHttpPort()+"");
        map.put("rpcPort", springProperties.getRpcPort()+"");
        String jsonPayload = JsonConverter.objectToJson(map);

        String api = String.format("%s/api/oss/store/node", springProperties.getConsoleEndpoint());
        HttpClient httpClient = HttpClient.newBuilder().build();
        HttpRequest httpRequest = HttpRequest.newBuilder(new URI(api))
                .header("content-type", "application/json")
                .POST(HttpRequest.BodyPublishers.ofString(jsonPayload))
                .build();
        HttpResponse<String> httpResponse = httpClient.send(httpRequest, HttpResponse.BodyHandlers.ofString());
        int statusCode = httpResponse.statusCode();
        String body = httpResponse.body();
        if (statusCode != 200) {
            String errMsg = String.format("%s -> %s", statusCode, body);
            throw new Exception(errMsg);
        }

        Type type = new TypeToken<WebResult<String>>(){}.getType();
        WebResult<String> webResult = JsonConverter.jsonToObject(body, type);
        if (webResult.getCode() != 0) {
            String errMsg = String.format("%s - %s", webResult.getCode(), webResult.getMsg());
            throw new Exception(errMsg);
        }
    }

    @Override
    public void destroy() {
    }
}
