// Copyright (c) 2009-2026 SAP SE, All Rights Reserved

sap.ui.define([
    "sap/ui/core/mvc/Controller",
    "sap/ui/model/json/JSONModel",
    "sap/ushell/resources",
    "sap/ushell/Config",
    "sap/ushell/utils/workpage/UserHomeService",
    "sap/ushell/utils/workpage/WorkPageService"
], (
    Controller,
    JSONModel,
    resources,
    Config,
    UserHomeService,
    WorkPageService
) => {
    "use strict";

    return Controller.extend("sap.ushell.components.shell.Settings.mySpace.MySpaceSetting", {

        onInit: function () {
            const oViewData = this.getView().getViewData();
            this.oUserInfoService = oViewData.UserInfo;
            this.oUser = this.oUserInfoService.getUser();

            this.oWorkPageService = new WorkPageService();
            this.sSiteId = Config.last("/core/site/siteId");
            // To keep it modular, this flag controls whether the workpage is deleted or just hidden when the user disables MySpace.
            this.bDeleteOnDisable = Config.last("/core/workPages/userHome/deleteOnDisable");

            const oModel = new JSONModel({
                showMySpace: false,
                initialShowMySpace: false,
                deleteOnDisable: this.bDeleteOnDisable
            });
            this.getView().setModel(oModel);
            this.getView().setModel(resources.i18nModel, "i18n");

            // Load initial value from adapter
            UserHomeService.isEnabled().then((bMySpaceEnabled) => {
                this.bInitialShowMySpace = bMySpaceEnabled;
                oModel.setProperty("/showMySpace", bMySpaceEnabled);
                oModel.setProperty("/initialShowMySpace", bMySpaceEnabled);
            });
        },

        onSave: function () {
            const oModel = this.getView().getModel();
            const bOldShowMySpace = this.bInitialShowMySpace;
            const bNewShowMySpace = oModel.getProperty("/showMySpace");

            // Nothing to do if setting has not been changed
            if (bOldShowMySpace === bNewShowMySpace) {
                return Promise.resolve();
            }

            // Toggle My Space via adapter (persists in backend)
            return this._toggleMySpace(bNewShowMySpace)
                .then(() => {
                    return {
                        refresh: true,
                        noHash: true
                    };
                })
                .catch((oError) => {
                    // Revert on error
                    oModel.setProperty("/showMySpace", bOldShowMySpace);
                    throw oError;
                });
        },

        /**
         * Creates a workpage (or reuses an existing one) and stores the workpageId and enable flag.
         * If a workpageId is already stored in the personalization data the page was only hidden before, not deleted,
         * so we reuse the existing id and skip the creation call.
         * @since 1.147.0
         * @private
         */
        async _enableMySpace () {
            const oPersData = await UserHomeService.getPersData();

            if (oPersData.workpageId) {
                // Workpage already exists (was only hidden) – just re-enable it
                await UserHomeService.setPersData({ enabled: true, workpageId: oPersData.workpageId });
                return;
            }

            const oResult = await this.oWorkPageService.createUserHomePage();
            const sWorkpageId = oResult?.data?.createUserWorkPage;
            await UserHomeService.setPersData({ enabled: true, workpageId: sWorkpageId });
        },
        /**
         * Deletes or hides the workpage based on configuration and updates the personalization.
         * When hiding (bDeleteOnDisable is false) the workpageId is intentionally preserved so
         * that a subsequent _enableMySpace() call can reuse the existing page instead of creating a new one.
         * @since 1.147.0
         * @private
         */
        async _disableMySpace () {
            if (this.bDeleteOnDisable) {
                await this.oWorkPageService.deleteUserWorkPage();
                await UserHomeService.setPersData({ enabled: false, workpageId: null });
                return;
            }
            // Preserve the workpageId so _enableMySpace() can reuse the existing page
            const oPersData = await UserHomeService.getPersData();
            await UserHomeService.setPersData({ enabled: false, workpageId: oPersData.workpageId });
        },

        /**
         * Toggles My Space (personal workpage) on or off.
         *
         * @param {boolean} bEnabled - Whether My Space should be enabled
         * @returns {Promise} Promise resolving when the operation completes
         * @private
         */
        _toggleMySpace: async function (bEnabled) {
            if (bEnabled) {
                await this._enableMySpace();
            } else {
                await this._disableMySpace();
            }
        },

        onCancel: function () {
            this.getView().getModel().setProperty("/showMySpace", this.bInitialShowMySpace);
        }

    });
});

