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 a=1;for(;r?.folder;)r=await t.get(r.folder),a++;if(a>=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;const r=this.folder||null,{deleteContents:i,deleteSubfolders:a}=e,o=[],n=[],s=await this.getSubfolders(!0);for(let e of s)a?o.push(e.id):n.push(e.id);if(o.length&&(await this.constructor.sublevel.delMany(o),db.DatabaseBackend.emit(this.documentName,"delete",o,{pack:this.pack,render:!0},t)),n.length){await this.constructor.sublevel.findUpdate({_id__in:Array.from(n)},{folder:r});const e=n.map((e=>({_id:e,folder:r})));db.DatabaseBackend.emit(this.documentName,"update",e,{pack:this.pack,render:!0},t)}if("Compendium"===this.type)return;o.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(o)}),l.length&&db.DatabaseBackend.emit(this.type,"delete",l.map((e=>e._id)),{pack:this.pack,render:!0},t);else{const e=await d.findUpdate({folder__in:Array.from(o)},{folder:r});if(e.length){const i=e.map((e=>({_id:e._id,folder:r})));db.DatabaseBackend.emit(this.type,"update",i,{pack:this.pack,render:!0},t)}}logger.info([`Deleting Folder [${this.id}] also deletes:`,o.length>1?o.length-1+" subfolders":"",l.length?`and ${l.length} ${this.type} documents`:""].filterJoin(" "))}}function migrateParentToFolder(e){return Folder._addDataFieldMigration(e,"parent","folder")}