package com.bocloud.ims.service.scheduler.scheduler;


import com.alibaba.fastjson.JSON;
import com.bocloud.cmp.driver.compute.ServerDriver;
import com.bocloud.cmp.entity.enums.CloudProvider;
import com.bocloud.cmp.model.NetworkCardModel;
import com.bocloud.cmp.model.ServerModel;
import com.bocloud.common.model.BocloudResult;
import com.bocloud.ims.entity.resource.CloudServer;
import com.bocloud.ims.entity.resource.CloudVendor;
import com.bocloud.ims.entity.resource.NetworkCard;
import com.bocloud.ims.interfaces.resource.CloudVendorService;
import com.bocloud.ims.repository.resource.CloudServerRepository;
import com.bocloud.ims.repository.resource.NetworkCardRepository;
import com.bocloud.service.core.CurrentService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Objects;
import java.util.Optional;

/**
 * SmartX定时更新任务
 */
@Component
public class SmartScheduler {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private CurrentService service;
    @Autowired
    private ServerDriver serverDriver;
    @Autowired
    private CloudVendorService cloudVendorService;
    @Autowired
    private CloudServerRepository cloudServerRepository;
    @Autowired
    private NetworkCardRepository networkCardRepository;

    @Scheduled(cron = "${smart.process.scheduler:0 0/5 * * * ?}")
    public void processCloudServer() {
        if (!service.isLeader()) {
            return;
        }
        logger.info("开始定时更新Smart-X云主机...");
        List<CloudVendor> vendors = this.cloudVendorService.listAll();
        for (CloudVendor vendor : vendors) {
            if (CloudProvider.SMARTX.name().equals(vendor.getType())) {
                BocloudResult bocloudResult = serverDriver.list(vendor.getUuid(), null);
                if (bocloudResult.isFailed()) {
                    logger.error("获取Smart-X平台[" + vendor.getName() + "]的所有云主机信息失败：" + bocloudResult.getMessage());
                    continue;
                }
                List<ServerModel> serverModels = (List<ServerModel>) bocloudResult.getData();
                if (serverModels != null && serverModels.size() > 0) {
                    for (ServerModel serverModel : serverModels) {
                        CloudServer cloudServer = cloudServerRepository.getByInstanceId(serverModel.getInstanceId());
                        if (cloudServer == null) {
                            logger.info("发现Smart-X平台[" + vendor.getName() + "]存在云主机[" + serverModel.getName() + "]而CMP中不存在该云主机，已忽略");
                            continue;
                        }
                        if (!Objects.equals(cloudServer.getManagerIp(), serverModel.getManagerIp())) {
                            cloudServer.setManagerIp(serverModel.getManagerIp());
                            cloudServerRepository.update(cloudServer);
                            logger.info("更新Smart-X平台[" + vendor.getName() + "]云主机[" + serverModel.getName() + "]管理IP为["
                                    + serverModel.getManagerIp() + "]");
                        }
                        String privateIps = JSON.toJSONString(serverModel.getIps());
                        if (!Objects.equals(cloudServer.getPrivateIps(), privateIps)) {
                            cloudServer.setPrivateIps(privateIps);
                            cloudServerRepository.update(cloudServer);
                            logger.info("更新Smart-X平台[" + vendor.getName() + "]云主机[" + serverModel.getName() + "]私有IP为["
                                    + privateIps + "]");
                        }
                        if (!Objects.equals(cloudServer.getOsVersion(), serverModel.getOsVersion())) {
                            cloudServer.setOsVersion(serverModel.getOsVersion());
                            cloudServerRepository.update(cloudServer);
                            logger.info("更新Smart-X平台[" + vendor.getName() + "]云主机[" + serverModel.getName() + "]操作系统为["
                                    + serverModel.getOsVersion() + "]");
                        }

                        List<NetworkCard> networkCards = networkCardRepository.listByHost(cloudServer.getId(), "VM");
                        for (NetworkCardModel networkCardModel : serverModel.getNetworkCards()) {
                            Optional<NetworkCard> networkCardOpt = networkCards.stream()
                                    .filter(dbNetworkCard -> Objects.equals(networkCardModel.getMac(), dbNetworkCard.getMac())).findFirst();
                            if (!networkCardOpt.isPresent()) {
                                logger.info("发现Smart-X平台[" + vendor.getName() + "]云主机[" + serverModel.getName() + "]" +
                                        "存在网卡[" + networkCardModel.getMac() + "]而CMP中不存在该网卡，已忽略");
                                continue;
                            }
                            NetworkCard networkCard = networkCardOpt.get();
                            if (!Objects.equals(networkCard.getIpAddress(), networkCardModel.getIpAddress())) {
                                networkCard.setIpAddress(networkCardModel.getIpAddress());
                                networkCardRepository.update(networkCard);
                                logger.info("更新Smart-X平台[" + vendor.getName() + "]云主机[" + serverModel.getName() + "]网卡" +
                                        "[" + networkCardModel.getMac() + "]的IP地址为[" + networkCardModel.getIpAddress() + "]");
                            }
                        }
                    }
                }

            }
        }
        logger.info("定时更新Smart-X云主机完成");
    }
}
