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 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547

import type { FileInfo } from "@/FileSystem/FileInfo";
import { _convertTreeNodeList } from "@/FileSystem/LoadSaveMolModels/ConvertMolModels/_ConvertTreeNodeList";
import { parseAndLoadMoleculeFile } from "@/FileSystem/LoadSaveMolModels/ParseMolModels/ParseMoleculeFiles";
import { ILoadMolParams } from "@/FileSystem/LoadSaveMolModels/ParseMolModels/Types";
import { getFormatInfoGivenType } from "@/FileSystem/LoadSaveMolModels/Types/MolFormats";
import { messagesApi } from "@/Api/Messages";
import type { ITreeNode, TreeNode } from "../TreeNode/TreeNode";
import { TreeNodeListCopies } from "./_Copy";
import { EasyCriterion, TreeNodeListFilters } from "./_Filters";
import { TreeNodeListNodeActions } from "./_NodeActions";
import { randomID } from "@/Core/Utils/MiscUtils";

/**
 * TreeNodeList class
 */
export class TreeNodeList {
    public _nodes: TreeNode[] = [];
    private _filters: TreeNodeListFilters;
    private _nodeActions: TreeNodeListNodeActions;
    private _copy: TreeNodeListCopies;
    public triggerId = ""; // Purpose of this is just to trigger reactivity if needed

    // This is to keep track of titles. It takes a surprisingly long time to
    // generate this set on the fly.
    // private _titles: Set<string> = new Set<string>();

    /**
     * Constructor.
     *
     * @param  {TreeNode[]} [nodes] The nodes to add to the list.
     */
    constructor(nodes?: TreeNode[]) {
        if (nodes) {
            this._nodes = nodes;
            // this._updateTitles();
        }

        this._filters = new TreeNodeListFilters(this);
        this._nodeActions = new TreeNodeListNodeActions(this);
        this._copy = new TreeNodeListCopies(this);

        // For chaining
        return this;
    }

    /**
     * Triggers reactivity. This is useful on rare occasions you need to trigger
     * reactivity explicitly. Tested on the main, root node. May work on others.
     */
    public triggerReactivity() {
        this.triggerId = randomID();

        this.nodes = this.nodes.map((n) => n);

        for (const node of this.nodes) {
            node.triggerReactivity();
            node.nodes?.triggerReactivity();
        }
    }

    // private _updateTitles(): void {
    //     this._titles = new Set<string>();
    //     this._nodes.forEach((node) => {
    //         this._titles.add(node.title);
    //     });
    // }

    /**
     * Gets the filters.
     *
     * @returns {TreeNodeListFilters}  The filters.
     */
    public get filters(): TreeNodeListFilters {
        return this._filters;
    }

    /**
     * Gets the copy actions.
     *
     * @returns {TreeNodeListCopies}  The copy actions.
     */
    public get copy(): TreeNodeListCopies {
        return this._copy;
    }

    /**
     * Gets the nodes as an array.
     *
     * @returns {TreeNode[]}  The nodes.
     */
    public get nodes(): TreeNode[] {
        return this._nodes;
    }

    /**
     * Sets the nodes.
     *
     * @param  {TreeNode[]} nodes  The nodes.
     */
    public set nodes(nodes: TreeNode[]) {
        this._nodes = nodes;
        // this._updateTitles();
    }

    /**
     * An easy way to look up nodes in the descendency. Can be a list of
     * criteria (one criteria per level) or a single criteria.
     *
     * @param  {EasyCriterion[]|EasyCriterion} searchCriteria  The criteria.
     * @returns {TreeNodeList}  The nodes that match the criteria.
     */
    public lookup(
        searchCriteria: EasyCriterion[] | EasyCriterion
    ): TreeNodeList {
        return this._filters.lookup(searchCriteria);
    }

    /**
     * Add a node to the list.
     *
     * @param  {TreeNode} node  The node to add.
     */
    public push(node: TreeNode) {
        // let newTitle = node.title;

        // if (this._titles.size > 0) {
        //     // Does node.title already exist in this list? If so, rename it.
        //     let idx = 0;
        //     while (this._titles.has(newTitle)) {
        //         newTitle = node.title + " (" + ++idx + ")";
        //     }
        //     this._titles.add(newTitle);
        // }

        // node.title = newTitle;

        // // Throw warning if title already exists.
        // const titles = this._nodes.map((n) => n.title);

        // console.log("titles", titles);

        // // If the title already exists, throw warning.
        // if (titles.includes(node.title)) {
        //     const msg =
        //         "Warning: Node with title " +
        //         node.title +
        //         " already exists. When adding nodes, try to make them unique to avoid problems in the data panel!";
        //     // if (GlobalVars.isLocalHost) {
        //     //     alert(msg);
        //     // }
        //     console.warn(msg);
        // }

        this._nodes.push(node);
    }

    /**
     * Gets the number of nodes in this list.
     *
     * @returns {number}  The number of nodes.
     */
    public get length(): number {
        return this._nodes.length;
    }

    /**
     * Gets the node at the specified index.
     *
     * @param  {number} index  The index.
     * @returns {TreeNode}  The node.
     */
    public get(index: number): TreeNode {
        return this._nodes[index];
    }

    /**
     * Sets the node at the specified index.
     *
     * @param  {number}   index  The index.
     * @param  {TreeNode} node   The node.
     */
    public set(index: number, node: TreeNode) {
        this._nodes[index] = node;
    }

    /**
     * Iterates through the nodes.
     *
     * @param {Function} func  The function to call for each node.
     */
    public forEach(func: (node: TreeNode, index: number) => void) {
        for (let i = 0; i < this._nodes.length; i++) {
            func(this._nodes[i], i);
        }
    }

    /**
     * Filters the nodes.
     *
     * @param  {Function} func  The function to call for each node. If the
     *                          function returns true, the node is included in
     *                          the result.
     * @returns {TreeNodeList}  The filtered nodes.
     */
    public filter(
        func: (node: TreeNode, index: number, array: any) => boolean
    ): TreeNodeList {
        return new TreeNodeList(this._nodes.filter(func));
    }

    /**
     * Gets the first node in the list that matches the specified criteria.
     *
     * @param  {Function} func  The function to call for each node. If the
     *                          function returns true, the node is included in
     *                          the result.
     * @returns {TreeNode|undefined}  The first node that matches the criteria,
     *     or undefined if no nodes match the criteria.
     */
    public find(
        func: (node: TreeNode, index?: number, array?: any) => boolean
    ): TreeNode | undefined {
        return this._nodes.find(func);
    }

    /**
     * Maps the nodes to a new array.
     *
     * @param  {Function} func  The function to call for each node. The function
     *                          should return the new value for the node.
     * @returns {any[]}  The mapped values.
     */
    public map(
        func: (node: TreeNode, index?: number, array?: any) => any
    ): any[] {
        return this._nodes.map(func);
    }

    /**
     * Removes the first node in the list and returns it.
     *
     * @returns {TreeNode|undefined}  The node that was removed, or undefined if
     *     the list is empty.
     */
    public shift(): TreeNode | undefined {
        // const firstElement = this._nodes.shift();
        // if (firstElement !== undefined) {
        //     this._titles.delete(firstElement.title);
        // }
        return this._nodes.shift();
    }

    /**
     * Inserts new elements at the start of the list, and returns the new length
     * of the list.
     *
     * @param  {TreeNode} node  The node to insert.
     * @returns {number}  The new length of the list.
     */
    public unshift(node: TreeNode): number {
        // this._titles.add(node.title);
        return this._nodes.unshift(node);
    }

    /**
     * Removes the last element from the list and returns it. If the list is
     * empty, undefined is returned and the list is not modified.
     *
     * @returns {TreeNode|undefined}  The node that was removed, or undefined if
     *     the list is empty.
     */
    public pop(): TreeNode | undefined {
        // const lastElement = this._nodes.pop();
        // if (lastElement !== undefined) {
        //     this._titles.delete(lastElement.title);
        // }
        return this._nodes.pop();
    }

    /**
     * Adds all the nodes in the specified list to this list. Acts in place, but
     * also returns this list for chaining.
     *
     * @param  {TreeNodeList} nodeList  The list of nodes to add.
     * @returns {TreeNodeList}  This list.
     */
    public extend(nodeList: TreeNodeList): TreeNodeList {
        nodeList.forEach((node: TreeNode) => {
            this.push(node);
        });
        return this;
    }

    /**
     * Calls the specified callback function for all the elements in the list.
     * The return value of the callback function is the accumulated result, and
     * is provided as an argument in the next call to the callback function.
     *
     * @param  {Function} func            The function to call for each node.
     *                                    The function should return the new
     *                                    value for the accumulator.
     * @param  {any}      [initialValue]  The initial value for the accumulator.
     * @returns {any}  The accumulated result.
     */
    public reduce(
        func: (
            accumulator: any,
            node: TreeNode,
            index?: number,
            array?: any
        ) => any,
        initialValue?: any
    ): any {
        return this._nodes.reduce(func, initialValue);
    }

    /**
     * Tests whether at least one element in the list passes the test
     * implemented by the provided function.
     *
     * @param  {Function} func  The function to test for each element.
     * @returns {boolean}  `true` if the callback function returns a truthy
     *         value for at least one element in the list. Otherwise, `false`.
     */
    public some(
        func: (node: TreeNode, index?: number, array?: TreeNode[]) => boolean
    ): boolean {
        return this._nodes.some(func);
    }

    /**
     * Sorts the nodes.
     *
     * @param {Function} func  The function to call for each node. The function
     *                         should return a number indicating the sort order.
     * @returns {TreeNodeList}  This list, sorted (for chaining).
     */
    public sort(func: (a: TreeNode, b: TreeNode) => number): TreeNodeList {
        this._nodes.sort(func);
        return this;
    }

    /**
     * Gets the nodes as an array.
     *
     * @returns {TreeNode[]}  The nodes.
     */
    public toArray(): TreeNode[] {
        return this._nodes;
    }

    /**
     * Gets the nodes as a serialized array of ITreeNode interfaces. Good for
     * saving to JSON or passing to webworker.
     *
     * @returns {ITreeNode[]}  The serialized nodes.
     */
    public serialize(): ITreeNode[] {
        return this._nodes.map((node: TreeNode) => {
            return node.serialize();
        });
    }

    /**
     * Clears the list of nodes.
     */
    public clear() {
        this._nodes = [];
        // this._titles.clear();
    }

    /**
     * Loads a molecule into the list.
     *
     * @deprecated Use `parseAndLoadMoleculeFile` from `FileSystem` instead.
     * @param  {ILoadMolParams} params  The parameters for loading the molecule.
     * @returns {Promise<void | TreeNodeList>}  A promise that resolves with the
     *     list of new nodes, or undefined on failure.
     */
    public async loadFromFileInfo(
        params: ILoadMolParams
    ): Promise<void | TreeNodeList> {
        return parseAndLoadMoleculeFile(params);
    }

    /**
     * Remove a node of given id, as well as any childless nodes that result.
     * In-place operation.
     *
     * @param  {string | TreeNode | null} node  The id of the node to remove, or
     *                                          the node itself.
     */
    public removeNode(node: string | TreeNode | null) {
        // if (typeof node === "string") {
        //     // If it's a string
        //     this._titles.delete(node);
        // } else if (node) {
        //     // It's a TreeNode
        //     this._titles.delete(node.title);
        // }
        this._nodeActions.remove(node);
    }

    /**
     * Gets all the nodes, whether terminal or not.
     *
     * @returns {TreeNodeList}  The flat array of all nodes.
     */
    public get flattened(): TreeNodeList {
        return this._nodeActions.flattened;
    }

    /**
     * An alias for filters.onlyTerminal. Gets all the terminal nodes. You
     * access this offten enough that it's easier to add this alias.
     *
     * @returns {TreeNodeList}  All the terminal nodes.
     */
    public get terminals(): TreeNodeList {
        return this._filters.onlyTerminal;
    }

    /**
     * Convert this TreeNodeList to a specified molecular format.
     *
     * @param  {string}          targetExt      The extension of the format to
     *                                          convert to.
     * @param  {boolean}         [merge=true]  Whether to merge the models into
     *                                          a single PDB string.
     * @returns {FileInfo[]} The text-formatted (e.g., PDB, MOL2) strings.
     */
    public async toFileInfos(
        targetExt: string,
        merge = true
    ): Promise<FileInfo[]> {
        // Determine if in worker
        const inWorker =
            // eslint-disable-next-line @typescript-eslint/ban-ts-comment
            // @ts-ignore
            typeof WorkerGlobalScope !== "undefined" &&
            // eslint-disable-next-line @typescript-eslint/ban-ts-comment
            // @ts-ignore
            self instanceof WorkerGlobalScope;

        const formatInfo = getFormatInfoGivenType(targetExt);

        // Start spinner
        let spinnerId: any;
        if (!inWorker) {
            spinnerId = messagesApi.startWaitSpinner();
        }

        const fileInfos = await _convertTreeNodeList(this, targetExt, merge);

        // Update the molecule name in the fileInfo contents
        for (let i = 0; i < fileInfos.length; i++) {
            if (formatInfo && formatInfo.updateMolNameInContents) {
                fileInfos[i].contents = formatInfo.updateMolNameInContents(
                    fileInfos[i].contents,
                    this._nodes[i].title
                );
            }
        }

        if (!inWorker) {
            messagesApi.stopWaitSpinner(spinnerId);
        }

        return fileInfos;
    }

    /**
     * A helper function tht adds all the nodes in this list to the molecules in
     * the vuex store.
     *
     * @param {string | null} tag  The tag to add to the main tree.
     * @param {boolean} [reassignIds=true] Whether to reassign IDs to the new
     *    nodes to avoid collisions. Set to false
     *    when loading a saved session.
     * @param {boolean} [terminalNodeTitleRevisable=true] Whether the title of
     *             the terminal node
     *             should be revisable.
     *             Revised if there is
     *             only one terminal
     *             node. If you're adding
     *             nodes incrementally,
     *             good to set to false.
     * @param {boolean} [resetVisibilityAndSelection=true] Whether to make the molecule
     *            visible and unselected. Set to false
     *            when loading a saved session where these
     *            properties should be preserved.
     */
    public addToMainTree(
        tag: string | null,
        reassignIds = true,
        terminalNodeTitleRevisable = true,
        resetVisibilityAndSelection = true
    ) {
        for (const node of this._nodes) {
            node.addToMainTree(
                tag,
                reassignIds,
                terminalNodeTitleRevisable,
                resetVisibilityAndSelection
            );
        }
    }

    /**
     * A helper function that creates a new TreeNodeList. This is useful for
     * avoiding circular dependencies.
     *
     * @param  {TreeNode[]} [nodes=[]]  The nodes to add to the new list.
     * @returns {TreeNodeList}  The new list.
     */
    public newTreeNodeList(nodes: TreeNode[] = []): TreeNodeList {
        // To avoid circular dependencies
        return new TreeNodeList(nodes);
    }

    /**
     * Merges all the nodes in this list into a single node. This is useful for
     * converting a list of molecules into a single molecule.
     *
     * @param  {string} [topLevelTitle=undefined]  The title of the top-level
     *                                             node. If undefined, the title
     *                                             of the first node is used.
     * @returns {TreeNodeList}  The new list.
     */
    public merge(topLevelTitle?: string): TreeNodeList {
        // This is where the title is being set to first item. Bad if multiple
        // frames!
        const firstNode = this._nodes[0].shallowCopy();

        if (topLevelTitle) {
            firstNode.title = topLevelTitle;
        }

        for (let i = 1; i < this._nodes.length; i++) {
            const node = this._nodes[i];
            firstNode.mergeInto(node);
        }
        return new TreeNodeList([firstNode]);
    }
}