import BaseFolder from"../../../common/documents/folder.mjs";import ServerDocumentMixin from"../backend/server-document.mjs";import{SORT_INTEGER_DENSITY}from"../../../common/constants.mjs";export default class Folder extends(ServerDocumentMixin(BaseFolder)){static _migrationRegistry=[...super._migrationRegistry,{fn:migrateParentToFolder,version:12}];async getSubfolders(e=!1,t){if((t=t||new Set).has(this.id))return[];let r=await this.constructor.find({folder:this.id});if(t.add(this.id),e&&r.length)for(let e of r){const i=await e.getSubfolders(!0,t);r=r.concat(i)}return r}async _preCreate(e,t,r){if(!Number.isFinite(this.sort)){const e=await Folder.find({type:this.type});let t=Math.max(...e.map(e=>e.sort||0));this.updateSource({sort:t+SORT_INTEGER_DENSITY})}if(e.folder){const t=e.pack?db.packs.get(e.pack).folders:db.Folder;let r=await t.get(e.folder);if(!r)return;const i=e.pack?CONST.FOLDER_MAX_DEPTH-1:CONST.FOLDER_MAX_DEPTH;let o=1;for(;r?.folder;)r=await t.get(r.folder),o++;if(o>=i)throw new Error(`You may not nest Folders more than ${i} levels deep.`)}if(this.compendium&&this.compendium.packData.type!==this.type)throw new Error(`Attempted to create a Folder for ${this.type} Documents in a compendium that only allows for ${this.compendium.packData.type} Documents.`);return super._preCreate(e,t,r)}async _preUpdate(e,t,r){if(!1===await super._preUpdate(e,t,r))return!1;if(e.parent&&e.parent===this.id)throw new Error("You cannot assign a Folder to be it's own parent")}async _preDelete(e,t){if(!1===await super._preDelete(e,t))return!1;if(e.dryRun)return;const r=this.folder||null,{deleteContents:i,deleteSubfolders:o}=e,s=[],n=[],a=await this.getSubfolders(!0);for(const e of a)o?s.push(e.id):n.push(e.id);if(s.length&&(await this.constructor.sublevel.delMany(s),e._sideEffects.push({type:this.documentName,action:"delete",result:s,operation:{pack:this.pack,render:!0}})),n.length){await this.constructor.sublevel.findUpdate({_id__in:Array.from(n)},{folder:r});const t=n.map(e=>({_id:e,folder:r}));e._sideEffects.push({type:this.documentName,action:"update",result:t,operation:{pack:this.pack,render:!0}})}if("Compendium"===this.type)return;s.push(this.id);const d=this.pack?this.compendium.sublevel:db[this.type].implementation.sublevel;let l=[];if(i)l=await d.findDelete({folder__in:Array.from(s)}),l.length&&e._sideEffects.push({type:this.type,action:"delete",result:l.map(e=>e._id),operation:{pack:this.pack,render:!0}});else{const t=await d.findUpdate({folder__in:Array.from(s)},{folder:r});if(t.length){const i=t.map(e=>({_id:e._id,folder:r}));e._sideEffects.push({type:this.type,action:"update",result:i,operation:{pack:this.pack,render:!0}})}}logger.info([`Deleting Folder [${this.id}] also deletes:`,s.length>1?s.length-1+" subfolders":"",l.length?`and ${l.length} ${this.type} documents`:""].filterJoin(" "))}}function migrateParentToFolder(e){return Folder._addDataFieldMigration(e,"parent","folder")}