package com.bocloud.ims.service.resource.h3c;

import com.bocloud.cmp.driver.compute.HostPoolDriver;
import com.bocloud.cmp.entity.enums.CloudProvider;
import com.bocloud.cmp.model.VDCModel;
import com.bocloud.common.model.BocloudResult;
import com.bocloud.common.model.OperateResult;
import com.bocloud.common.model.RequestContext;
import com.bocloud.common.utils.MapTools;
import com.bocloud.ims.entity.resource.CloudVendor;
import com.bocloud.ims.entity.resource.Server;
import com.bocloud.ims.entity.resource.Vdc;
import com.bocloud.ims.interfaces.h3c.H3cHostPoolService;
import com.bocloud.ims.repository.resource.CloudServerRepository;
import com.bocloud.ims.repository.resource.CloudVendorRepository;
import com.bocloud.ims.repository.resource.ClusterRepository;
import com.bocloud.ims.repository.resource.DataStoreFileRepository;
import com.bocloud.ims.repository.resource.DataStoreRepository;
import com.bocloud.ims.repository.resource.ImageRepository;
import com.bocloud.ims.repository.resource.IpRepository;
import com.bocloud.ims.repository.resource.NetworkCardRepository;
import com.bocloud.ims.repository.resource.NetworkHostRepository;
import com.bocloud.ims.repository.resource.NetworkRepository;
import com.bocloud.ims.repository.resource.ResourceRepository;
import com.bocloud.ims.repository.resource.ServerConfigRepository;
import com.bocloud.ims.repository.resource.ServerRepository;
import com.bocloud.ims.repository.resource.SnapshotRepository;
import com.bocloud.ims.repository.resource.StoreHostRepository;
import com.bocloud.ims.repository.resource.SwitcherRepository;
import com.bocloud.ims.repository.resource.VdcRepository;
import com.bocloud.ims.repository.resource.VolumeRepository;
import com.bocloud.ims.service.utils.ResourceEventPublisher;
import com.bocloud.ims.service.utils.SyncH3cUtils;
import com.google.common.collect.Lists;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service("h3cHostPoolService")
public class H3cHostPoolServiceImpl implements H3cHostPoolService {

	private Logger logger = LoggerFactory.getLogger(this.getClass());

	@Autowired
	private VdcRepository vdcRepository;

	@Autowired
	private CloudVendorRepository cloudVendorRepository;

	@Autowired
	private HostPoolDriver hostPoolDriver;

	@Autowired
	private ResourceEventPublisher resourceEventPublisher;
	@Autowired
	private CloudServerRepository cloudServerRepository;
	@Autowired
	private ServerRepository serverRepository;
	@Autowired
	private SnapshotRepository snapshotRepository;
	@Autowired
	private NetworkRepository networkRepository;
	@Autowired
	private ClusterRepository clusterRepository;
	@Autowired
	private StoreHostRepository storeHostRepository;
	@Autowired
	private NetworkCardRepository networkCardRepository;
	@Autowired
	private NetworkHostRepository networkHostRepository;
	@Autowired
	private ServerConfigRepository serverConfigRepository;
	@Autowired
	private ResourceRepository resourceRepository;
	@Autowired
	private IpRepository ipRepository;
	@Autowired
	private ImageRepository imageRepository;
	@Autowired
	private VolumeRepository volumeRepository;
	@Autowired
	private DataStoreFileRepository dataStoreFileRepository;
	@Autowired
	private SwitcherRepository switcherRepository;
	@Autowired
	private DataStoreRepository dataStoreRepository;

	@Override
	public BocloudResult<String> create(Vdc model, RequestContext context) {
		try {
			Long vendorId = model.getVendorId();
			CloudVendor vendor = cloudVendorRepository.query(vendorId);
			if (null == vendor) {
				return new BocloudResult<String>(false, "获取云供应商失败");
			}
			boolean flag = vdcRepository.exists(model.getName(), model.getVendorId());
			if (flag) {
				return new BocloudResult<String>(false, "该主机池已经存在");
			}
			new Thread(() -> {
				String operate = vendor.getType().toLowerCase() + ".hostpool";
				String msgContent = "主机池创建失败";
				VDCModel vdcModel = new VDCModel();
				vdcModel.setName(model.getName());
				BocloudResult result = hostPoolDriver.create(vendor.getUuid(), vdcModel);
				try {
					if (result.isSuccess()) {
						msgContent = "主机池创建成功";
						// 同步集群
						BocloudResult<VDCModel> bocloudResult = hostPoolDriver.detail(vendor.getUuid(),
								model.getName());
						VDCModel h3cVdcModel = bocloudResult.getData();
						String name = model.getName();
						BeanUtils.copyProperties(h3cVdcModel, model);
						model.setName(name);
						model.setType(CloudProvider.H3C.name());
						model.setCreatorId(context.getTarget());
						model.setVendorId(vendorId);
						model.setMenderId(context.getTarget());
						model.setUuid(h3cVdcModel.getVdcVal());
						vdcRepository.save(model);
						resourceEventPublisher.send(new OperateResult(true, msgContent, operate,
								MapTools.simpleMap("vendorId", vendor.getId()),
								OperateResult.OperateCategory.ResourceEvent, context));
					}
				} catch (Exception e) {
					logger.error("Get error message:", e);
					resourceEventPublisher.send(new OperateResult(false, msgContent, operate,
							MapTools.simpleMap("vendorId", vendor.getId()), OperateResult.OperateCategory.ResourceEvent,
							context));
				}
			}).start();
			return new BocloudResult<String>(true, "主机池创建任务已下发，正在执行...");
		} catch (Exception e) {
			logger.error("create cluster error", e);
			return new BocloudResult<String>(false, "创建主机池失败");
		}
	}

	@Override
	public BocloudResult<String> remove(Long vdcId, RequestContext context) {
		try {
			Vdc vdc = vdcRepository.query(vdcId);
			String vdcVal = vdc.getVdcVal();
			Long vendorId = vdc.getVendorId();
			CloudVendor vendor = cloudVendorRepository.query(vendorId);
			if (null == vendor) {
				return new BocloudResult<String>(false, "获取云供应商失败");
			}
			new Thread(() -> {
				try {
					BocloudResult bocloudResult = hostPoolDriver.remove(vendor.getUuid(), vdcVal);
					if (bocloudResult.isSuccess()) {
						vdcRepository.remove(vdcId, context.getTarget());
						SyncH3cUtils syncH3cUtils = new SyncH3cUtils(cloudServerRepository, serverRepository,
								snapshotRepository, dataStoreRepository, networkRepository, clusterRepository,
								storeHostRepository, networkCardRepository, networkHostRepository,
								serverConfigRepository, resourceRepository, ipRepository, imageRepository,
								volumeRepository, dataStoreFileRepository, switcherRepository, vdcRepository);
						clusterRepository.removeByVdc(vdcId, context.getTarget());
						List<Server> servers = serverRepository.listByVdc(vdcId);
						for (Server server : servers) {
							syncH3cUtils.removeHostCascade(server, context.getTarget(), null);
						}
						resourceEventPublisher.send(new OperateResult(true, "删除主机池成功", "h3c.hostpool",
								MapTools.simpleMap("vendorId", vendor.getId()),
								OperateResult.OperateCategory.ResourceEvent, context));
					} else {
						resourceEventPublisher.send(new OperateResult(false, "删除主机池失败:" + bocloudResult.getMessage(),
								"h3c.hostpool", MapTools.simpleMap("vendorId", vendor.getId()),
								OperateResult.OperateCategory.ResourceEvent, context));
					}
				} catch (Exception e) {
					logger.error("删除主机池失败", e);
					resourceEventPublisher.send(new OperateResult(false, "删除主机池失败:" + e.getMessage(), "h3c.hostpool",
							MapTools.simpleMap("vendorId", vendor.getId()), OperateResult.OperateCategory.ResourceEvent,
							context));
				}
			}).start();

		} catch (Exception e) {
			logger.error("delete hostpool error", e);
			return new BocloudResult<String>(false, "删除主机池失败:" + e.getMessage());
		}
		return new BocloudResult<String>(true, "删除任务下发......");
	}
}
