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

import com.bocloud.cmp.driver.common.TaskMsgDriver;
import com.bocloud.cmp.model.h3c.H3cTaskMsgModel;
import com.bocloud.common.model.BocloudResult;
import com.bocloud.common.model.OperateResult;
import com.bocloud.common.model.RequestContext;
import com.bocloud.common.model.RequestContext.Catalog;
import com.bocloud.common.utils.MapTools;
import com.bocloud.ims.entity.resource.CloudVendor;
import com.bocloud.ims.service.utils.ResourceEventPublisher;

public abstract class H3cCommonService {

    protected abstract ResourceEventPublisher getResourceEventPublisher();

    protected abstract TaskMsgDriver getTaskMsgDriver();

    public void sendMessage(Boolean isSuccess, Long managerId, CloudVendor vendor, String operate, String tips,
                            OperateResult.OperateCategory operateCategory) {
        OperateResult message;
        message = new OperateResult(isSuccess, tips, operate, MapTools.simpleMap("vendorId", vendor.getId()),
                operateCategory, new RequestContext(Catalog.Manager, managerId, 0L, null, null));

        getResourceEventPublisher().send(message);
    }

    public BocloudResult<H3cTaskMsgModel> queryTaskResult(CloudVendor vendor, Long msgId, Long start, Long timeout)
            throws InterruptedException {
        H3cTaskMsgModel msgModel;
        boolean running = true;
        while (running) {
            BocloudResult bocloudResult = getTaskMsgDriver().get(msgId, vendor.getUuid());
            if (bocloudResult.isSuccess()) {
                msgModel = (H3cTaskMsgModel) bocloudResult.getData();
                if (msgModel.getCompleted()) {
                    if (msgModel.getResult().equals(0)) {
                        return new BocloudResult<H3cTaskMsgModel>(true, msgModel, "成功");
                    } else {
                        return new BocloudResult<H3cTaskMsgModel>(false, msgModel.getDetail());
                    }
                }
            }
            Thread.sleep(2000L);
            if (System.currentTimeMillis() - start > timeout) {
                running = false;
            }
        }
        return new BocloudResult<>(false, "查询失败");
    }
}
