var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __metadata = (this && this.__metadata) || function (k, v) {
    if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
import logger from "../../../../Utils/Logger";
import ComponentCode from "../../ComponentCode";
import BaseModel from "../../../../../Models/DatabaseModels/DatabaseBaseModel/DatabaseBaseModel";
import BadDataException from "../../../../../Types/Exception/BadDataException";
import Exception from "../../../../../Types/Exception/Exception";
import JSONFunctions from "../../../../../Types/JSONFunctions";
import Text from "../../../../../Types/Text";
import BaseModelComponents from "../../../../../Types/Workflow/Components/BaseModel";
import CaptureSpan from "../../../../Utils/Telemetry/CaptureSpan";
export default class CreateOneBaseModel extends ComponentCode {
    constructor(modelService) {
        super();
        this.modelService = null;
        const BaseModelComponent = BaseModelComponents.getComponents(modelService.getModel()).find((i) => {
            return (i.id ===
                `${Text.pascalCaseToDashes(modelService.getModel().tableName)}-create-one`);
        });
        if (!BaseModelComponent) {
            throw new BadDataException("Create one component for " +
                modelService.getModel().tableName +
                " not found.");
        }
        this.setMetadata(BaseModelComponent);
        this.modelService = modelService;
    }
    async run(args, options) {
        const successPort = this.getMetadata().outPorts.find((p) => {
            return p.id === "success";
        });
        if (!successPort) {
            throw options.onError(new BadDataException("Success port not found"));
        }
        const errorPort = this.getMetadata().outPorts.find((p) => {
            return p.id === "error";
        });
        if (!errorPort) {
            throw options.onError(new BadDataException("Error port not found"));
        }
        try {
            if (!this.modelService) {
                throw options.onError(new BadDataException("modelService is undefined."));
            }
            if (!args["json"]) {
                throw options.onError(new BadDataException("JSON is undefined."));
            }
            if (typeof args["json"] === "string") {
                args["json"] = JSONFunctions.parse(args["json"]);
            }
            if (typeof args["json"] !== "object") {
                throw options.onError(new BadDataException("JSON is should be of type object."));
            }
            if (this.modelService.getModel().getTenantColumn()) {
                args["json"][this.modelService.getModel().getTenantColumn()] = options.projectId;
            }
            const model = (await this.modelService.create({
                data: BaseModel.fromJSON(args["json"] || {}, this.modelService.modelType),
                props: {
                    isRoot: true,
                    tenantId: options.projectId,
                },
            }));
            return {
                returnValues: {
                    model: BaseModel.toJSON(model, this.modelService.modelType),
                },
                executePort: successPort,
            };
        }
        catch (err) {
            logger.error(err);
            if (err instanceof Exception) {
                options.log(err.getMessage());
            }
            else {
                options.log(err.message ? err.message : JSON.stringify(err, null, 2));
            }
            return {
                returnValues: {},
                executePort: errorPort,
            };
        }
    }
}
__decorate([
    CaptureSpan(),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [Object, Object]),
    __metadata("design:returntype", Promise)
], CreateOneBaseModel.prototype, "run", null);
//# sourceMappingURL=CreateOneBaseModel.js.map