import { UMB_USER_DETAIL_REPOSITORY_ALIAS } from '../../repository/index.js';
import { UMB_USER_ENTITY_TYPE } from '../../entity.js';
import { UmbUserAvatarRepository } from '../../repository/avatar/index.js';
import { UmbUserConfigRepository } from '../../repository/config/index.js';
import { UmbUserWorkspaceEditorElement } from './user-workspace-editor.element.js';
import { UMB_USER_WORKSPACE_ALIAS } from './constants.js';
import { UmbEntityNamedDetailWorkspaceContextBase } from '../../../../core/workspace/index.js';
import { UmbObjectState } from '../../../../../libs/observable-api/index.js';
export class UmbUserWorkspaceContext extends UmbEntityNamedDetailWorkspaceContextBase {
    #calculatedStartNodes;
    constructor(host) {
        super(host, {
            workspaceAlias: UMB_USER_WORKSPACE_ALIAS,
            entityType: UMB_USER_ENTITY_TYPE,
            detailRepositoryAlias: UMB_USER_DETAIL_REPOSITORY_ALIAS,
        });
        this.avatarRepository = new UmbUserAvatarRepository(this);
        this.configRepository = new UmbUserConfigRepository(this);
        this.state = this._data.createObservablePartOfCurrent((x) => x?.state);
        this.kind = this._data.createObservablePartOfCurrent((x) => x?.kind);
        this.userGroupUniques = this._data.createObservablePartOfCurrent((x) => x?.userGroupUniques || []);
        this.documentStartNodeUniques = this._data.createObservablePartOfCurrent((data) => data?.documentStartNodeUniques || []);
        this.hasDocumentRootAccess = this._data.createObservablePartOfCurrent((data) => data?.hasDocumentRootAccess || false);
        this.mediaStartNodeUniques = this._data.createObservablePartOfCurrent((data) => data?.mediaStartNodeUniques || []);
        this.hasMediaRootAccess = this._data.createObservablePartOfCurrent((data) => data?.hasMediaRootAccess || false);
        this.#calculatedStartNodes = new UmbObjectState(undefined);
        this.calculatedStartNodes = this.#calculatedStartNodes.asObservable();
        this.routes.setRoutes([
            {
                path: 'edit/:id',
                component: UmbUserWorkspaceEditorElement,
                setup: (_component, info) => {
                    const id = info.match.params.id;
                    this.load(id);
                },
            },
        ]);
    }
    async load(unique) {
        const response = await super.load(unique);
        if (!response.data) {
            // Return early if there is no user	data
            this.removeUmbControllerByAlias('umbUserStoreObserver');
            return response;
        }
        this.observe(response.asObservable?.(), (user) => this.onUserStoreChanges(user), 'umbUserStoreObserver');
        if (!this._detailRepository) {
            throw new Error('Detail repository is missing');
        }
        // Get the calculated start nodes
        const { data: calculatedStartNodes } = await this._detailRepository.requestCalculateStartNodes(unique);
        this.#calculatedStartNodes.setValue(calculatedStartNodes);
        return response;
    }
    /* Some properties are allowed to update without saving.
        For a user, properties like state will be updated when one of the entity actions are executed.
        Therefore we have to subscribe to the user store to update the state in the workspace data.
        We update both current and persisted so these server-applied changes do not trigger dirty state.
        There might be a less manual way to do this.
    */
    onUserStoreChanges(user) {
        if (user) {
            const serverAppliedChanges = { state: user.state, avatarUrls: user.avatarUrls };
            this._data.updateCurrent(serverAppliedChanges);
            this._data.updatePersisted(serverAppliedChanges);
        }
    }
    getState() {
        return this._data.getCurrent()?.state;
    }
    updateProperty(propertyName, value) {
        this._data.updateCurrent({ [propertyName]: value });
    }
    // TODO: implement upload progress
    uploadAvatar(file) {
        const unique = this.getUnique();
        if (!unique)
            throw new Error('Id is missing');
        return this.avatarRepository.uploadAvatar(unique, file);
    }
    async deleteAvatar() {
        const unique = this.getUnique();
        if (!unique)
            throw new Error('Id is missing');
        await this.avatarRepository.deleteAvatar(unique);
    }
    destroy() {
        this.avatarRepository.destroy();
        super.destroy();
    }
}
export { UmbUserWorkspaceContext as api };
