"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const errors_1 = require("../errors");
const getTrashFolderId_1 = require("../services/trash/getTrashFolderId");
const test_utils_1 = require("../testing/test-utils");
const Folder_1 = require("./Folder");
const Note_1 = require("./Note");
const Setting_1 = require("./Setting");
async function allItems() {
    const folders = await Folder_1.default.all();
    const notes = await Note_1.default.all();
    return folders.concat(notes);
}
describe('models/Folder', () => {
    beforeEach(async () => {
        await (0, test_utils_1.setupDatabaseAndSynchronizer)(1);
        await (0, test_utils_1.switchClient)(1);
    });
    it('should tell if a folder can be nested under another one', (async () => {
        const f1 = await Folder_1.default.save({ title: 'folder1' });
        const f2 = await Folder_1.default.save({ title: 'folder2', parent_id: f1.id });
        const f3 = await Folder_1.default.save({ title: 'folder3', parent_id: f2.id });
        const f4 = await Folder_1.default.save({ title: 'folder4' });
        expect(await Folder_1.default.canNestUnder(f1.id, f2.id)).toBe(false);
        expect(await Folder_1.default.canNestUnder(f2.id, f2.id)).toBe(false);
        expect(await Folder_1.default.canNestUnder(f3.id, f1.id)).toBe(true);
        expect(await Folder_1.default.canNestUnder(f4.id, f1.id)).toBe(true);
        expect(await Folder_1.default.canNestUnder(f2.id, f3.id)).toBe(false);
        expect(await Folder_1.default.canNestUnder(f3.id, f2.id)).toBe(true);
        expect(await Folder_1.default.canNestUnder(f1.id, '')).toBe(true);
        expect(await Folder_1.default.canNestUnder(f2.id, '')).toBe(true);
    }));
    it('should recursively delete notes and sub-folders', (async () => {
        const f1 = await Folder_1.default.save({ title: 'folder1' });
        const f2 = await Folder_1.default.save({ title: 'folder2', parent_id: f1.id });
        const f3 = await Folder_1.default.save({ title: 'folder3', parent_id: f2.id });
        const f4 = await Folder_1.default.save({ title: 'folder4', parent_id: f1.id });
        const noOfNotes = 20;
        await (0, test_utils_1.createNTestNotes)(noOfNotes, f1, null, 'note1');
        await (0, test_utils_1.createNTestNotes)(noOfNotes, f2, null, 'note2');
        await (0, test_utils_1.createNTestNotes)(noOfNotes, f3, null, 'note3');
        await (0, test_utils_1.createNTestNotes)(noOfNotes, f4, null, 'note4');
        await Folder_1.default.delete(f1.id);
        const all = await allItems();
        expect(all.length).toBe(0);
    }));
    it('should sort by last modified, based on content', (async () => {
        let folders;
        const f1 = await Folder_1.default.save({ title: 'folder1' });
        await (0, test_utils_1.sleep)(0.1);
        const f2 = await Folder_1.default.save({ title: 'folder2' });
        await (0, test_utils_1.sleep)(0.1);
        const f3 = await Folder_1.default.save({ title: 'folder3' });
        await (0, test_utils_1.sleep)(0.1);
        const n1 = await Note_1.default.save({ title: 'note1', parent_id: f2.id });
        folders = await Folder_1.default.orderByLastModified(await Folder_1.default.all(), 'desc');
        expect(folders.length).toBe(3);
        expect(folders[0].id).toBe(f2.id);
        expect(folders[1].id).toBe(f3.id);
        expect(folders[2].id).toBe(f1.id);
        await Note_1.default.save({ title: 'note1', parent_id: f1.id });
        folders = await Folder_1.default.orderByLastModified(await Folder_1.default.all(), 'desc');
        expect(folders[0].id).toBe(f1.id);
        expect(folders[1].id).toBe(f2.id);
        expect(folders[2].id).toBe(f3.id);
        await Note_1.default.save({ id: n1.id, title: 'note1 mod' });
        folders = await Folder_1.default.orderByLastModified(await Folder_1.default.all(), 'desc');
        expect(folders[0].id).toBe(f2.id);
        expect(folders[1].id).toBe(f1.id);
        expect(folders[2].id).toBe(f3.id);
        folders = await Folder_1.default.orderByLastModified(await Folder_1.default.all(), 'asc');
        expect(folders[0].id).toBe(f3.id);
        expect(folders[1].id).toBe(f1.id);
        expect(folders[2].id).toBe(f2.id);
    }));
    it('should sort by last modified, based on content (sub-folders too)', (async () => {
        let folders;
        const f1 = await Folder_1.default.save({ title: 'folder1' });
        await (0, test_utils_1.sleep)(0.1);
        const f2 = await Folder_1.default.save({ title: 'folder2' });
        await (0, test_utils_1.sleep)(0.1);
        const f3 = await Folder_1.default.save({ title: 'folder3', parent_id: f1.id });
        await (0, test_utils_1.sleep)(0.1);
        const n1 = await Note_1.default.save({ title: 'note1', parent_id: f3.id });
        folders = await Folder_1.default.orderByLastModified(await Folder_1.default.all(), 'desc');
        expect(folders.length).toBe(3);
        expect(folders[0].id).toBe(f1.id);
        expect(folders[1].id).toBe(f3.id);
        expect(folders[2].id).toBe(f2.id);
        await Note_1.default.save({ title: 'note2', parent_id: f2.id });
        folders = await Folder_1.default.orderByLastModified(await Folder_1.default.all(), 'desc');
        expect(folders[0].id).toBe(f2.id);
        expect(folders[1].id).toBe(f1.id);
        expect(folders[2].id).toBe(f3.id);
        await Note_1.default.save({ id: n1.id, title: 'note1 MOD' });
        folders = await Folder_1.default.orderByLastModified(await Folder_1.default.all(), 'desc');
        expect(folders[0].id).toBe(f1.id);
        expect(folders[1].id).toBe(f3.id);
        expect(folders[2].id).toBe(f2.id);
        const f4 = await Folder_1.default.save({ title: 'folder4', parent_id: f1.id });
        await (0, test_utils_1.sleep)(0.1);
        await Note_1.default.save({ title: 'note3', parent_id: f4.id });
        folders = await Folder_1.default.orderByLastModified(await Folder_1.default.all(), 'desc');
        expect(folders.length).toBe(4);
        expect(folders[0].id).toBe(f1.id);
        expect(folders[1].id).toBe(f4.id);
        expect(folders[2].id).toBe(f3.id);
        expect(folders[3].id).toBe(f2.id);
    }));
    it('should add node counts', (async () => {
        const f1 = await Folder_1.default.save({ title: 'folder1' });
        const f2 = await Folder_1.default.save({ title: 'folder2', parent_id: f1.id });
        const f3 = await Folder_1.default.save({ title: 'folder3', parent_id: f2.id });
        const f4 = await Folder_1.default.save({ title: 'folder4' });
        await Note_1.default.save({ title: 'note1', parent_id: f3.id });
        await Note_1.default.save({ title: 'note1', parent_id: f3.id });
        await Note_1.default.save({ title: 'note1', parent_id: f1.id });
        await Note_1.default.save({ title: 'conflicted', parent_id: f1.id, is_conflict: 1 });
        {
            const folders = await Folder_1.default.all({ includeConflictFolder: false });
            await Folder_1.default.addNoteCounts(folders);
            // eslint-disable-next-line @typescript-eslint/no-explicit-any -- Old code before rule was applied
            const foldersById = {};
            // eslint-disable-next-line github/array-foreach -- Old code before rule was applied
            folders.forEach((f) => { foldersById[f.id] = f; });
            expect(folders.length).toBe(4);
            expect(foldersById[f1.id].note_count).toBe(3);
            expect(foldersById[f2.id].note_count).toBe(2);
            expect(foldersById[f3.id].note_count).toBe(2);
            expect(foldersById[f4.id].note_count).toBe(0);
        }
        {
            const folders = await Folder_1.default.all({ includeConflictFolder: true });
            await Folder_1.default.addNoteCounts(folders);
            // eslint-disable-next-line @typescript-eslint/no-explicit-any -- Old code before rule was applied
            const foldersById = {};
            // eslint-disable-next-line github/array-foreach -- Old code before rule was applied
            folders.forEach((f) => { foldersById[f.id] = f; });
            expect(folders.length).toBe(5);
            expect(foldersById[Folder_1.default.conflictFolderId()].note_count).toBe(1);
        }
    }));
    it('folder hierarchy cycles should not cause addNoteCounts to loop infinitely', async () => {
        const f1 = await Folder_1.default.save({ title: 'folder1' });
        const f2 = await Folder_1.default.save({ title: 'folder2', parent_id: f1.id });
        const f3 = await Folder_1.default.save({ title: 'folder3', parent_id: f2.id });
        await Note_1.default.save({ title: 'test', parent_id: f1.id });
        // Create a cycle.
        // Note: This has been observed to happen, likely as a result of a bug in other code.
        await Folder_1.default.save({ id: f1.id, parent_id: f3.id });
        const folders = await Folder_1.default.all();
        // Should not loop indefinitely, okay to warn:
        await (0, test_utils_1.withWarningSilenced)(/has itself as a parent/, async () => {
            await Folder_1.default.addNoteCounts(folders);
        });
        // Note count may be incorrect
        expect(folders.find(folder => folder.id === f1.id)).toHaveProperty('note_count');
    });
    it('should not count completed to-dos', (async () => {
        const f1 = await Folder_1.default.save({ title: 'folder1' });
        const f2 = await Folder_1.default.save({ title: 'folder2', parent_id: f1.id });
        const f3 = await Folder_1.default.save({ title: 'folder3', parent_id: f2.id });
        const f4 = await Folder_1.default.save({ title: 'folder4' });
        await Note_1.default.save({ title: 'note1', parent_id: f3.id });
        await Note_1.default.save({ title: 'note2', parent_id: f3.id });
        await Note_1.default.save({ title: 'note3', parent_id: f1.id });
        await Note_1.default.save({ title: 'note4', parent_id: f3.id, is_todo: 1, todo_completed: 0 });
        await Note_1.default.save({ title: 'note5', parent_id: f3.id, is_todo: 1, todo_completed: 999 });
        await Note_1.default.save({ title: 'note6', parent_id: f3.id, is_todo: 1, todo_completed: 999 });
        const folders = await Folder_1.default.all();
        await Folder_1.default.addNoteCounts(folders, false);
        // eslint-disable-next-line @typescript-eslint/no-explicit-any -- Old code before rule was applied
        const foldersById = {};
        // eslint-disable-next-line github/array-foreach -- Old code before rule was applied
        folders.forEach((f) => { foldersById[f.id] = f; });
        expect(folders.length).toBe(4);
        expect(foldersById[f1.id].note_count).toBe(4);
        expect(foldersById[f2.id].note_count).toBe(3);
        expect(foldersById[f3.id].note_count).toBe(3);
        expect(foldersById[f4.id].note_count).toBe(0);
    }));
    it('should recursively find folder path', (async () => {
        const f1 = await Folder_1.default.save({ title: 'folder1' });
        const f2 = await Folder_1.default.save({ title: 'folder2', parent_id: f1.id });
        const f3 = await Folder_1.default.save({ title: 'folder3', parent_id: f2.id });
        const folders = await Folder_1.default.all();
        const folderPath = await Folder_1.default.folderPath(folders, f3.id);
        expect(folderPath.length).toBe(3);
        expect(folderPath[0].id).toBe(f1.id);
        expect(folderPath[1].id).toBe(f2.id);
        expect(folderPath[2].id).toBe(f3.id);
    }));
    it('should sort folders alphabetically including deleted folders', (async () => {
        const f1 = await Folder_1.default.save({ title: 'folder1' });
        const f2 = await Folder_1.default.save({ title: 'folder2', parent_id: f1.id });
        const f3 = await Folder_1.default.save({ title: 'folder3', parent_id: f1.id });
        const f4 = await Folder_1.default.save({ title: 'folder4' });
        const f5 = await Folder_1.default.save({ title: 'folder5', parent_id: f4.id });
        const f6 = await Folder_1.default.save({ title: 'folder6' });
        await Folder_1.default.delete(f1.id, { toTrash: true });
        await Folder_1.default.delete(f5.id, { toTrash: true });
        const folders = await Folder_1.default.allAsTree();
        const sortedFolderTree = await Folder_1.default.sortFolderTree(folders);
        expect(sortedFolderTree.length).toBe(3);
        expect(sortedFolderTree[0].id).toBe(f1.id);
        expect(sortedFolderTree[0].children[0].id).toBe(f2.id);
        expect(sortedFolderTree[0].children[1].id).toBe(f3.id);
        expect(sortedFolderTree[1].id).toBe(f4.id);
        expect(sortedFolderTree[1].children[0].id).toBe(f5.id);
        expect(sortedFolderTree[2].id).toBe(f6.id);
    }));
    it('should sort folders alphabetically excluding deleted folders', (async () => {
        const f1 = await Folder_1.default.save({ title: 'folder1' });
        const f2 = await Folder_1.default.save({ title: 'folder2' });
        const f3 = await Folder_1.default.save({ title: 'folder3', parent_id: f2.id });
        const f4 = await Folder_1.default.save({ title: 'folder4' });
        await Folder_1.default.delete(f1.id, { toTrash: true });
        await Folder_1.default.delete(f3.id, { toTrash: true });
        const folders = await Folder_1.default.allAsTree();
        const sortedFolderTree = await Folder_1.default.sortFolderTree(folders, { includeDeleted: false });
        expect(sortedFolderTree.length).toBe(2);
        expect(sortedFolderTree[0].id).toBe(f2.id);
        expect(sortedFolderTree[0].children.length).toBe(0);
        expect(sortedFolderTree[1].id).toBe(f4.id);
    }));
    it('should sort folders with special chars alphabetically', (async () => {
        const unsortedFolderTitles = ['ç', 'd', 'c', 'Ä', 'b', 'a'].map(firstChar => `${firstChar} folder`);
        for (const folderTitle of unsortedFolderTitles) {
            await Folder_1.default.save({ title: folderTitle });
        }
        const folders = await Folder_1.default.allAsTree();
        const sortedFolderTree = await Folder_1.default.sortFolderTree(folders);
        // same set of titles, but in alphabetical order
        const sortedFolderTitles = ['a', 'Ä', 'b', 'c', 'ç', 'd'].map(firstChar => `${firstChar} folder`);
        expect(sortedFolderTree.map(f => f.title)).toEqual(sortedFolderTitles);
    }));
    it('should sort numbers ascending', (async () => {
        const unsortedFolderTitles = ['10', '1', '2'].map(firstChar => `${firstChar} folder`);
        for (const folderTitle of unsortedFolderTitles) {
            await Folder_1.default.save({ title: folderTitle });
        }
        const folders = await Folder_1.default.allAsTree();
        const sortedFolderTree = await Folder_1.default.sortFolderTree(folders);
        // same set of titles, but in ascending order
        const sortedFolderTitles = ['1', '2', '10'].map(firstChar => `${firstChar} folder`);
        expect(sortedFolderTree.map(f => f.title)).toEqual(sortedFolderTitles);
    }));
    it('should not allow setting a folder parent as itself', (async () => {
        const f1 = await Folder_1.default.save({ title: 'folder1' });
        const hasThrown = await (0, test_utils_1.checkThrowAsync)(() => Folder_1.default.save({ id: f1.id, parent_id: f1.id }, { userSideValidation: true }));
        expect(hasThrown).toBe(true);
    }));
    it('should get all the children of a folder', (async () => {
        const folder = await (0, test_utils_1.createFolderTree)('', [
            {
                title: 'folder 1',
                children: [
                    {
                        title: 'note 1',
                    },
                    {
                        title: 'note 2',
                    },
                    {
                        title: 'folder 2',
                        children: [
                            {
                                title: 'note 3',
                            },
                        ],
                    },
                    {
                        title: 'folder 3',
                        children: [],
                    },
                ],
            },
            {
                title: 'folder 4',
                children: [
                    {
                        title: 'folder 5',
                        children: [],
                    },
                ],
            },
        ]);
        const folder2 = await Folder_1.default.loadByTitle('folder 2');
        const folder3 = await Folder_1.default.loadByTitle('folder 3');
        const folder4 = await Folder_1.default.loadByTitle('folder 4');
        const folder5 = await Folder_1.default.loadByTitle('folder 5');
        {
            const children = await Folder_1.default.allChildrenFolders(folder.id);
            expect(children.map(c => c.id).sort()).toEqual([folder2.id, folder3.id].sort());
        }
        {
            const children = await Folder_1.default.allChildrenFolders(folder4.id);
            expect(children.map(c => c.id).sort()).toEqual([folder5.id].sort());
        }
        {
            const children = await Folder_1.default.allChildrenFolders(folder5.id);
            expect(children.map(c => c.id).sort()).toEqual([].sort());
        }
    }));
    it('should not allow creating a new folder as a child of a read-only folder', async () => {
        const cleanup = (0, test_utils_1.simulateReadOnlyShareEnv)('123456789');
        const readonlyFolder = await Folder_1.default.save({ share_id: '123456789' });
        await (0, test_utils_1.expectThrow)(async () => Folder_1.default.save({ parent_id: readonlyFolder.id }), errors_1.ErrorCode.IsReadOnly);
        cleanup();
    });
    it('should not allow moving a folder as a child of a read-only folder', async () => {
        const cleanup = (0, test_utils_1.simulateReadOnlyShareEnv)('123456789');
        const readonlyFolder = await Folder_1.default.save({ share_id: '123456789' });
        const folder = await Folder_1.default.save({});
        await (0, test_utils_1.expectThrow)(async () => Folder_1.default.save({ id: folder.id, parent_id: readonlyFolder.id }), errors_1.ErrorCode.IsReadOnly);
        cleanup();
    });
    it('should not allow modifying a read-only folder', async () => {
        const cleanup = (0, test_utils_1.simulateReadOnlyShareEnv)('123456789');
        const readonlyFolder = await Folder_1.default.save({ share_id: '123456789' });
        await (0, test_utils_1.expectThrow)(async () => Folder_1.default.save({ id: readonlyFolder.id, title: 'cannot do that' }), errors_1.ErrorCode.IsReadOnly);
        cleanup();
    });
    it('should not allow deleting a read-only folder', async () => {
        const cleanup = (0, test_utils_1.simulateReadOnlyShareEnv)('123456789');
        const readonlyFolder = await Folder_1.default.save({ share_id: '123456789' });
        await (0, test_utils_1.expectThrow)(async () => Folder_1.default.delete(readonlyFolder.id), errors_1.ErrorCode.IsReadOnly);
        cleanup();
    });
    it('should allow deleting a folder to trash', async () => {
        const folder1 = await Folder_1.default.save({});
        const folder2 = await Folder_1.default.save({});
        const note1 = await Note_1.default.save({ parent_id: folder1.id });
        const note2 = await Note_1.default.save({ parent_id: folder1.id });
        const note3 = await Note_1.default.save({ parent_id: folder2.id });
        const beforeTime = Date.now();
        await Folder_1.default.delete(folder1.id, { toTrash: true, deleteChildren: true });
        expect((await Folder_1.default.load(folder1.id)).deleted_time).toBeGreaterThanOrEqual(beforeTime);
        expect((await Folder_1.default.load(folder2.id)).deleted_time).toBe(0);
        expect((await Note_1.default.load(note1.id)).deleted_time).toBeGreaterThanOrEqual(beforeTime);
        expect((await Note_1.default.load(note2.id)).deleted_time).toBeGreaterThanOrEqual(beforeTime);
        expect((await Note_1.default.load(note3.id)).deleted_time).toBe(0);
    });
    it('should allow deleting multiple folders to trash', async () => {
        const folder1 = await Folder_1.default.save({});
        const folder2 = await Folder_1.default.save({});
        const folder3 = await Folder_1.default.save({ parent_id: folder2.id });
        const folder4 = await Folder_1.default.save({ parent_id: folder2.id });
        const beforeTime = Date.now();
        await Folder_1.default.batchDelete([folder1.id, folder2.id, folder3.id], { toTrash: true, deleteChildren: true });
        const folders = await Folder_1.default.loadItemsByIds([folder1.id, folder2.id, folder3.id, folder4.id]);
        expect(folders[0].deleted_time).toBeGreaterThanOrEqual(beforeTime);
        expect(folders[1].deleted_time).toBeGreaterThanOrEqual(beforeTime);
        expect(folders[2].deleted_time).toBeGreaterThanOrEqual(beforeTime);
        expect(folders[3].deleted_time).toBeGreaterThanOrEqual(beforeTime);
    });
    it('should delete and set the parent ID', async () => {
        const folder1 = await Folder_1.default.save({});
        const folder2 = await Folder_1.default.save({});
        await Folder_1.default.delete(folder1.id, { toTrash: true });
        await Folder_1.default.delete(folder2.id, { toTrash: true, toTrashParentId: folder1.id });
        expect((await Folder_1.default.load(folder2.id)).parent_id).toBe(folder1.id);
        // But it should not allow moving a folder to itself
        await (0, test_utils_1.expectThrow)(async () => Folder_1.default.delete(folder2.id, { toTrash: true, toTrashParentId: folder2.id }));
    });
    it('should filter out the trash folder and the deleted folders', async () => {
        let folders = [];
        expect(Folder_1.default.getRealFolders(folders).length).toBe(0);
        const folder1 = await Folder_1.default.save({});
        const folder2 = await Folder_1.default.save({ parent_id: folder1.id });
        const folder3 = await Folder_1.default.save({ parent_id: folder2.id });
        folders = await Folder_1.default.all();
        expect(Folder_1.default.getRealFolders(folders).sort((a, b) => a.created_time - b.created_time)).toEqual([folder1, folder2, folder3]);
        await Folder_1.default.delete(folder2.id, { toTrash: true });
        folders = await Folder_1.default.all();
        expect(Folder_1.default.getRealFolders(folders)).toEqual([folder1]);
        await Folder_1.default.delete(folder1.id, { toTrash: true });
        folders = await Folder_1.default.all();
        expect(Folder_1.default.getRealFolders(folders).length).toBe(0);
    });
    it('should tell if at least one folder other than trash and deleted exists', async () => {
        let folders = [];
        expect(Folder_1.default.atLeastOneRealFolderExists(folders)).toBe(false);
        folders = await Folder_1.default.all({ includeTrash: true });
        expect(Folder_1.default.atLeastOneRealFolderExists(folders)).toBe(false);
        const f1 = await Folder_1.default.save({ title: 'folder1' });
        folders = await Folder_1.default.all({ includeTrash: true });
        expect(Folder_1.default.atLeastOneRealFolderExists(folders)).toBe(true);
        await Folder_1.default.delete(f1.id, { toTrash: true });
        folders = await Folder_1.default.all({ includeTrash: true });
        expect(Folder_1.default.atLeastOneRealFolderExists(folders)).toBe(false);
    });
    it('should get active folder when activeFolderId is valid', async () => {
        const activeFolder = await Folder_1.default.save({ title: 'folder' });
        Setting_1.default.setValue('activeFolderId', activeFolder.id);
        const validFolder = await Folder_1.default.getValidActiveFolder();
        expect(validFolder.id).toBe(activeFolder.id);
    });
    it('should get default folder when activeFolderId is trashed', async () => {
        const defaultFolder = await Folder_1.default.save({ title: 'default' });
        const activeFolder = await Folder_1.default.save({ title: 'folder' });
        await Folder_1.default.delete(activeFolder.id, { toTrash: true });
        Setting_1.default.setValue('activeFolderId', activeFolder.id);
        const validFolder = await Folder_1.default.getValidActiveFolder();
        expect(validFolder.id).toBe(defaultFolder.id);
    });
    it('should get no folder when activeFolderId is undefined', async () => {
        Setting_1.default.setValue('activeFolderId', undefined);
        const validFolder = await Folder_1.default.getValidActiveFolder();
        expect(validFolder).toBeNull();
    });
    it('should get no folder when activeFolderId is trashed and there are no other not trashed folders', async () => {
        const activeFolder = await Folder_1.default.save({ title: 'folder' });
        const otherFolder = await Folder_1.default.save({ title: 'other' });
        await Folder_1.default.delete(activeFolder.id, { toTrash: true });
        await Folder_1.default.delete(otherFolder.id, { toTrash: true });
        Setting_1.default.setValue('activeFolderId', activeFolder.id);
        const validFolder = await Folder_1.default.getValidActiveFolder();
        expect(validFolder).toBeNull();
    });
    it('should get no folder when activeFolderId is a virtual folder', async () => {
        Setting_1.default.setValue('activeFolderId', (0, getTrashFolderId_1.default)());
        const validFolder = await Folder_1.default.getValidActiveFolder();
        expect(validFolder).toBeNull();
    });
});
//# sourceMappingURL=Folder.test.js.map