package com.bocloud.ims.service.builder;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.bocloud.acd.ims.symphony.resource.ApplyResourceCreator;
import com.bocloud.acd.ims.symphony.resource.factory.ResourceOperatorFactory;
import com.bocloud.acd.provider.factory.ProviderContextManager;
import com.bocloud.cmp.model.ServerModel;
import com.bocloud.cmp.vm.model.VmGenericParam;
import com.bocloud.common.model.BocloudResult;
import com.bocloud.ims.entity.resource.CloudServer;
import com.bocloud.ims.entity.resource.CloudVendor;

public class ResourceOperatorServerBuilder implements ServerBuilder {
    private ResourceOperatorFactory resourceOperatorFactory;
    private CloudVendor cloudVendor;
    ApplyResourceCreator<CloudServer, ServerModel, VmGenericParam> applyResourceCreator;
    CloudServer cloudServer;
    ServerModel serverModel;
    ProviderContextManager providerContextManager;

    public ResourceOperatorServerBuilder(ResourceOperatorFactory resourceOperatorFactory, CloudVendor cloudVendor, ProviderContextManager providerContextManager) {
        this.resourceOperatorFactory = resourceOperatorFactory;
        this.cloudVendor = cloudVendor;
        applyResourceCreator = this.resourceOperatorFactory.getApplyResourceCreator(this.cloudVendor.getType(), CloudServer.class, ServerModel.class, VmGenericParam.class);
        this.providerContextManager = providerContextManager;
    }

    @Override
    public BocloudResult<ServerModel> prepare(JSONObject object) throws Exception {
        VmGenericParam vmGenericParam = JSON.parseObject(object.toJSONString(), VmGenericParam.class);
        if (applyResourceCreator != null) {
            ServerModel prepare = applyResourceCreator.prepareApplyResource(vmGenericParam);
            return new BocloudResult<>(true, prepare, "");
        }
        return new BocloudResult<>(false, "不支持的资源面板，请检查是否有实现虚拟机的申请资源创建器");
    }

    @Override
    public void onConvertModelToEntity(ServerModel model, CloudServer entity) throws Exception {
        ServerBuilder.super.onConvertModelToEntity(model, entity);
        applyResourceCreator.onConvertModelToEntity(model, entity);
        this.serverModel = model;
        this.cloudServer = entity;
    }

    @Override
    public BocloudResult<CloudServer> builder(CloudServer server) throws Exception {
        providerContextManager.initAndSetContext(cloudVendor);
        CloudServer newCloudServer = applyResourceCreator.createApplyResource(server, serverModel);
        providerContextManager.remove();
        return new BocloudResult<>(true, newCloudServer, "创建完成");
    }
}
