import BaseSetting from"../../../common/documents/setting.mjs";import ServerDocumentMixin from"../backend/server-document.mjs";import{USER_PERMISSIONS,USER_ROLES}from"../../../common/constants.mjs";import{deepClone}from"../../../common/utils/helpers.mjs";export default class Setting extends(ServerDocumentMixin(BaseSetting)){_onCreate(e,t,i){super._onCreate(e,t,i),this.#e(),"core.moduleConfiguration"===this.key&&!1!==t.updateWorld&&game.world?.onUpdateModuleConfiguration(this.value)}_onUpdate(e,t,i){super._onUpdate(e,t,i),this.#e(),"core.moduleConfiguration"===this.key&&!1!==t.updateWorld&&game.world?.onUpdateModuleConfiguration(this.value)}async _preCreate(e,t,i){if(!1===await super._preCreate(e,t,i))return!1;if("core.moduleConfiguration"===this.key&&this.value){const e=deepClone(this.value);this.#t(e),this.updateSource({value:e})}}async _preUpdate(e,t,i){if(!1===await super._preUpdate(e,t,i))return!1;if("core.moduleConfiguration"===this.key&&"value"in e){const t=JSON.parse(e.value);this.#t(t),e.value=JSON.stringify(t)}}#e(){switch(this.key){case"core.permissions":game.permissions=this.value;break;case"core.compendiumConfiguration":game.compendiumConfiguration=this.value;break;case"core.time":game.activity.worldTime=parseInt(this.value)}}#t(e){const t=[...game.world.relationships.requires,...game.world.system.relationships.requires];for(const i of game.world.modules){const s=i.isCompatibleWithSystem(game.world.system),a=t.find((e=>e.id===i.id));s&&a?e[i.id]=!0:s||(e[i.id]=!1)}}static async getValue(e){const t=await this.findOne({key:e});return t?.value}static async set(e,t,i){t="string"==typeof t?t:JSON.stringify(t);let s=await this.find({key:e});return s.length?(s=s.shift(),s.update({value:t},i)):this.create({key:e,value:t},i)}static async getPermissions(){let e=await this.getValue("core.permissions")||{},t=!1;for(let[i,s]of Object.entries(USER_PERMISSIONS))i in e||(e[i]=Object.values(USER_ROLES).reduce(((e,t)=>(s.defaultRole<=t&&e.push(t),e)),[]),t=!0);return t&&await this.set("core.permissions",e),game.permissions=e}static async advanceTime(e,t,i){const s=await this.getValue("core.time")??0,a=await this.set("core.time",s+e);return db.DatabaseBackend.emit(this.documentName,"update",[{_id:a.id,value:a.value}],t,i),a}}