package com.bocloud.ims.service.thread;

import com.alibaba.fastjson.JSONObject;
import com.bocloud.cmp.driver.storage.VolumeDriver;
import com.bocloud.cmp.entity.enums.BocloudStatus;
import com.bocloud.cmp.model.VolumeModel;
import com.bocloud.common.model.BocloudResult;
import com.bocloud.common.model.BocloudResult;
import com.bocloud.common.model.RequestContext;
import com.bocloud.ims.entity.resource.CloudVendor;
import com.bocloud.ims.entity.resource.Volume;
import com.itextpdf.text.pdf.PdfStructTreeController.returnType;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;

/**
 * 腾讯云硬盘创建
 *
 * @author ymh
 * @时间 2019年1月14日
 */
public class PublicCloudVolumeBuilder implements VolumeBuilder {

	private static Logger logger = LoggerFactory.getLogger(PublicCloudVolumeBuilder.class);
	private VolumeDriver driver;
	private VolumeModel model;
	private String regionId;
	private CloudVendor vendor;
	private RequestContext context;

	/**
	 * @param driver
	 * @param model
	 * @param regionId
	 * @param vendor
	 * @param user
	 */
	public PublicCloudVolumeBuilder(VolumeDriver driver, VolumeModel model, String regionId, CloudVendor vendor,
			RequestContext context) {
		super();
		this.driver = driver;
		this.model = model;
		this.regionId = regionId;
		this.vendor = vendor;
		this.context = context;
	}

	@Override
	public BocloudResult<Volume> call() throws Exception {
		return build();
	}

	@Override
	public BocloudResult<Volume> build() {
		BocloudResult result = driver.create(vendor.getUuid(), regionId, model);
		if (result.isFailed()) {
			Volume volume = new Volume();
			BeanUtils.copyProperties(model, volume);
			return new BocloudResult<>(false, volume, result.getMessage());
		}
		Volume volume = JSONObject.parseObject(JSONObject.toJSONString(result.getData()), Volume.class);
		volume.setStatus(BocloudStatus.Server.BUILDING.name());
		volume.setRegion(regionId);
		volume.setRegionId(regionId);
		volume.preSave(context.getTarget(), context.getTarget(), context.getTenant(), vendor.getId(),
				context.getProject());
		volume.setOwnerId(context.getTarget());
		volume.setIops(model.getIops());
		Long start = System.currentTimeMillis();
		boolean running = true;
		while (running) {
			if (System.currentTimeMillis() - start > 1000 * 60 * 5) {
				volume.setStatus(BocloudStatus.Server.EXCEPTION.name());
				running = false;
				return new BocloudResult<>(false, volume, "云硬盘申请失败： 请求超时！");
			}
			result = driver.detail(volume.getVolumeUuid(), vendor.getUuid(), regionId);
			if (result.isSuccess()) {
				VolumeModel bean = JSONObject.parseObject(JSONObject.toJSONString(result.getData()), VolumeModel.class);
				String state = bean.getStatus();
				if ("AVAILABLE".equalsIgnoreCase(state) || "IN_USE".equalsIgnoreCase(state)
						|| "BACKING_UP".equalsIgnoreCase(state) || "UNATTACHED".equalsIgnoreCase(state)) {
					volume.setStatus(state);
					volume.setBootVolume(bean.getBootVolume());
					volume.setDeleteWithInstance(bean.getDeleteWithInstance());
					volume.setSourceSnapshotId(bean.getSourceSnapshotId());
					running = false;
				} else {
					try {
						Thread.sleep(3000L);
					} catch (InterruptedException e) {
						logger.error("thread sleep Exception : " + e);
						Thread.currentThread().interrupt();
					}
				}
			} else {
				logger.error("硬盘创建失败");
				volume.setStatus(BocloudStatus.Server.EXCEPTION.name());
				running = false;
				return new BocloudResult<>(false, volume, "云硬盘申请失败：" + result.getMessage());
			}
		}
		return new BocloudResult<>(true, volume, "硬盘申请成功！");
	}
}
