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.RequestContext;
import com.bocloud.ims.entity.resource.CloudVendor;
import com.bocloud.ims.entity.resource.OSTenant;
import com.bocloud.ims.entity.resource.Volume;
import com.bocloud.ims.interfaces.resource.VendorProjectService;
import com.bocloud.ims.repository.resource.OSTenantRepository;

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

public class OSVolumeBuilder implements VolumeBuilder {

	private static Logger logger = LoggerFactory.getLogger(OSVolumeBuilder.class);
	private VolumeDriver driver;
	private VolumeModel model;
	private String code;
	private CloudVendor vendor;
	private String region;
	private RequestContext context;
	private OSTenantRepository osTenantRepository;

	/**
	 * @param driver
	 * @param model
	 * @param code
	 * @param vendor
	 * @param region
	 * @param context
	 */
	public OSVolumeBuilder(VolumeDriver driver, VolumeModel model, String code, CloudVendor vendor, String region,
			RequestContext context, OSTenantRepository osTenantRepository) {
		super();
		this.driver = driver;
		this.model = model;
		this.code = code;
		this.vendor = vendor;
		this.region = region;
		this.context = context;
		this.osTenantRepository = osTenantRepository;
	}

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

	@Override
	public BocloudResult<Volume> build() {
		try {
			BocloudResult result = null;
			OSTenant osTenant = osTenantRepository.getByTenantId(context.getTenant(), vendor.getId());
			if (null == osTenant) {
				result = driver.create(vendor.getUuid(), code, model);
			} else {
				result = driver.create(vendor.getUuid(), osTenant.getName(), code, 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);
			String status = volume.getStatus();
			volume.setStatus(BocloudStatus.Server.BUILDING.name());
			volume.setRegion(region);
			volume.setZone(region);
			volume.preSave(context.getTarget(), context.getTarget(), context.getTenant(), vendor.getId(),
					context.getProject());
			volume.setOwnerId(context.getTarget());
			volume.setCatalog(context.getCatalog());
			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(), code);
				if (result.isSuccess()) {
					VolumeModel bean = JSONObject.parseObject(JSONObject.toJSONString(result.getData()),
							VolumeModel.class);
					String state = bean.getStatus();
					if (state.equalsIgnoreCase(status)) {
						try {
							Thread.sleep(3000L);
						} catch (InterruptedException e) {
							logger.error("OSVolumeBuilder get InterruptedException : ", e);
							Thread.currentThread().interrupt();
						}
					} else {
						volume.setStatus(state);
						running = false;
					}
				} else {
					volume.setStatus(BocloudStatus.Server.EXCEPTION.name());
					running = false;
					return new BocloudResult<>(false, volume, "云硬盘申请失败：" + result.getMessage());
				}
			}
			return new BocloudResult<>(true, volume, "success");
		} catch (Exception e) {
			logger.error("Get error message：{}", e);
			return new BocloudResult<>(false, e.getMessage());
		}
	}
}
