package com.jiayue.ipfcst.client;


import cn.hutool.json.JSONUtil;
import com.jiayue.ipfcst.client.domain.entity.ClientConfig;
import com.jiayue.ipfcst.client.utils.ClientFileUtils;
import com.jiayue.ipfcst.client.utils.Constant;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.embedded.tomcat.TomcatServletWebServerFactory;
import org.springframework.context.annotation.Bean;

import javax.annotation.PostConstruct;
import java.io.File;

@SpringBootApplication
@Slf4j
public class ClientApplication {


	public static void main(String[] args) {

		ClientFileUtils.ifFileNotExistToCreate("./default.properties");
		ClientFileUtils.ifFileNotExistToCreate("./clientConfig.properties");
		log.info("本地配置默认生成结束，开始启动client程序");
		SpringApplication.run(ClientApplication.class, args);
	}

	@PostConstruct
	private void init() throws Throwable {

		log.info("client启动成功-开始加载云预测参数");
		ClientConfig clientConfigLocal = new ClientConfig();
		try {
			clientConfigLocal = ClientFileUtils.syncClientConfig();
			log.info("client启动并加载云预测参数完成");
		}catch (Exception e) {
			try {
				log.info("client启动并加载云预测参数失败，加载本地配置文件。{}",e.getLocalizedMessage());
				clientConfigLocal = ClientFileUtils.loadLocalConfigFile();
			}catch (Exception e1) {
				log.info("client启动并加载加载本地配置文件失败。{}",e.getLocalizedMessage());
			}

		}
		Constant.cacheClientConfig = clientConfigLocal;
		log.info("场站编码：{} 启动成功，加载参数为：{}",Constant.cacheClientConfig.getStationCode(), JSONUtil.toJsonStr(Constant.cacheClientConfig));
	}

	@Bean
	public TomcatServletWebServerFactory servletContainer(){
		ClientFileUtils clientFileUtils = new ClientFileUtils();
		//应对AB机情况的外网初始化场站编码配置
		if(clientFileUtils.getPath().contains("-B")){
			return new TomcatServletWebServerFactory(81) ;
		}else{
			return new TomcatServletWebServerFactory(80);
		}

	}
}
