import { UMB_DOCUMENT_ENTITY_TYPE } from '../../entity.js';
import { UmbId } from '../../../../core/id/index.js';
import { DocumentService } from '../../../../core/backend-api/index.js';
import { tryExecute } from '../../../../core/resources/index.js';
import { umbDeepMerge } from '../../../../core/utils/index.js';
import { UmbDocumentTypeDetailServerDataSource } from '../../../document-types/index.js';
import { UmbControllerBase } from '../../../../../libs/class-api/index.js';
/**
 * A data source for the Document that fetches data from the server
 * @class UmbDocumentServerDataSource
 * @implements {RepositoryDetailDataSource}
 */
export class UmbDocumentServerDataSource extends UmbControllerBase {
    /**
     * Creates a new Document scaffold
     * @param preset
     * @returns { UmbDocumentDetailModel }
     * @memberof UmbDocumentServerDataSource
     */
    async createScaffold(preset = {}) {
        let documentTypeIcon = null;
        let documentTypeCollection = null;
        const documentTypeUnique = preset.documentType?.unique;
        if (!documentTypeUnique) {
            throw new Error('Document type unique is missing');
        }
        // TODO: investigate if we can use the repository here instead
        const { data } = await new UmbDocumentTypeDetailServerDataSource(this).read(documentTypeUnique);
        documentTypeIcon = data?.icon ?? null;
        documentTypeCollection = data?.collection ?? null;
        const defaultData = {
            entityType: UMB_DOCUMENT_ENTITY_TYPE,
            unique: UmbId.new(),
            template: null,
            documentType: {
                unique: documentTypeUnique,
                collection: documentTypeCollection,
                icon: documentTypeIcon,
            },
            isTrashed: false,
            values: [],
            variants: [],
            flags: [],
        };
        const scaffold = umbDeepMerge(preset, defaultData);
        return { data: scaffold };
    }
    /**
     * Fetches a Document with the given id from the server
     * @param {string} unique
     * @returns {*}
     * @memberof UmbDocumentServerDataSource
     */
    async read(unique) {
        if (!unique)
            throw new Error('Unique is missing');
        const { data, error } = await tryExecute(this, DocumentService.getDocumentById({ path: { id: unique } }));
        if (error || !data) {
            return { error };
        }
        // TODO: make data mapper to prevent errors
        const document = {
            entityType: UMB_DOCUMENT_ENTITY_TYPE,
            unique: data.id,
            values: data.values.map((value) => {
                return {
                    editorAlias: value.editorAlias,
                    culture: value.culture || null,
                    segment: value.segment || null,
                    alias: value.alias,
                    value: value.value,
                };
            }),
            variants: data.variants.map((variant) => {
                return {
                    culture: variant.culture || null,
                    segment: variant.segment || null,
                    state: variant.state,
                    name: variant.name,
                    publishDate: variant.publishDate || null,
                    createDate: variant.createDate,
                    updateDate: variant.updateDate,
                    scheduledPublishDate: variant.scheduledPublishDate || null,
                    scheduledUnpublishDate: variant.scheduledUnpublishDate || null,
                    flags: variant.flags,
                };
            }),
            template: data.template ? { unique: data.template.id } : null,
            documentType: {
                unique: data.documentType.id,
                collection: data.documentType.collection ? { unique: data.documentType.collection.id } : null,
                icon: data.documentType.icon,
            },
            isTrashed: data.isTrashed,
            flags: data.flags,
        };
        return { data: document };
    }
    /**
     * Inserts a new Document on the server
     * @param {UmbDocumentDetailModel} model - Document Model
     * @param parentUnique
     * @returns {*}
     * @memberof UmbDocumentServerDataSource
     */
    async create(model, parentUnique = null) {
        if (!model)
            throw new Error('Document is missing');
        if (!model.unique)
            throw new Error('Document unique is missing');
        // TODO: make data mapper to prevent errors
        const body = {
            id: model.unique,
            parent: parentUnique ? { id: parentUnique } : null,
            documentType: { id: model.documentType.unique },
            template: model.template ? { id: model.template.unique } : null,
            values: model.values,
            variants: model.variants,
        };
        const { data, error } = await tryExecute(this, DocumentService.postDocument({
            body: body,
        }));
        if (data) {
            return this.read(data);
        }
        return { error };
    }
    /**
     * Updates a Document on the server
     * @param {UmbDocumentDetailModel} model - Document Model
     * @returns {*}
     * @memberof UmbDocumentServerDataSource
     */
    async update(model) {
        if (!model.unique)
            throw new Error('Unique is missing');
        // TODO: make data mapper to prevent errors
        const body = {
            template: model.template ? { id: model.template.unique } : null,
            values: model.values,
            variants: model.variants,
        };
        const { error } = await tryExecute(this, DocumentService.putDocumentById({
            path: { id: model.unique },
            body: body,
        }));
        if (!error) {
            return this.read(model.unique);
        }
        return { error };
    }
    /**
     * Deletes a Document on the server
     * @param {string} unique
     * @returns {*}
     * @memberof UmbDocumentServerDataSource
     */
    async delete(unique) {
        if (!unique)
            throw new Error('Unique is missing');
        return tryExecute(this, DocumentService.deleteDocumentById({ path: { id: unique } }));
    }
}
