"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const base_command_1 = require("./base-command");
const app_1 = require("./app");
const locale_1 = require("@joplin/lib/locale");
const BaseModel_1 = require("@joplin/lib/BaseModel");
const Folder_1 = require("@joplin/lib/models/Folder");
const Setting_1 = require("@joplin/lib/models/Setting");
const Note_1 = require("@joplin/lib/models/Note");
const { sprintf } = require('sprintf-js');
const time_1 = require("@joplin/lib/time");
const { cliUtils } = require('./cli-utils.js');
class Command extends base_command_1.default {
    usage() {
        return 'ls [note-pattern]';
    }
    description() {
        return (0, locale_1._)('Displays the notes in the current notebook. Use `ls /` to display the list of notebooks.');
    }
    enabled() {
        return true;
    }
    options() {
        return [
            ['-n, --limit <num>', (0, locale_1._)('Displays only the first top <num> notes.')],
            ['-s, --sort <field>', (0, locale_1._)('Sorts the item by <field> (eg. title, updated_time, created_time).')],
            ['-r, --reverse', (0, locale_1._)('Reverses the sorting order.')],
            ['-t, --type <type>', (0, locale_1._)('Displays only the items of the specific type(s). Can be `n` for notes, `t` for to-dos, or `nt` for notes and to-dos (eg. `-tt` would display only the to-dos, while `-tnt` would display notes and to-dos.')],
            ['-f, --format <format>', (0, locale_1._)('Either "text" or "json"')],
            ['-l, --long', (0, locale_1._)('Use long list format. Format is ID, NOTE_COUNT (for notebook), DATE, TODO_CHECKED (for to-dos), TITLE')],
        ];
    }
    // eslint-disable-next-line @typescript-eslint/no-explicit-any -- Old code before rule was applied
    async action(args) {
        const pattern = args['note-pattern'];
        let items = [];
        const options = args.options;
        // eslint-disable-next-line @typescript-eslint/no-explicit-any -- Old code before rule was applied
        const queryOptions = {};
        if (options.limit)
            queryOptions.limit = options.limit;
        if (options.sort) {
            queryOptions.orderBy = options.sort;
            queryOptions.orderByDir = 'ASC';
        }
        if (options.reverse === true)
            queryOptions.orderByDir = queryOptions.orderByDir === 'ASC' ? 'DESC' : 'ASC';
        queryOptions.caseInsensitive = true;
        if (options.type) {
            queryOptions.itemTypes = [];
            if (options.type.indexOf('n') >= 0)
                queryOptions.itemTypes.push('note');
            if (options.type.indexOf('t') >= 0)
                queryOptions.itemTypes.push('todo');
        }
        if (pattern)
            queryOptions.titlePattern = pattern;
        queryOptions.uncompletedTodosOnTop = Setting_1.default.value('uncompletedTodosOnTop');
        let modelType = null;
        if (pattern === '/' || !(0, app_1.default)().currentFolder()) {
            queryOptions.includeConflictFolder = true;
            items = await Folder_1.default.all(queryOptions);
            modelType = Folder_1.default.modelType();
        }
        else {
            if (!(0, app_1.default)().currentFolder())
                throw new Error((0, locale_1._)('Please select a notebook first.'));
            items = await Note_1.default.previews((0, app_1.default)().currentFolder().id, queryOptions);
            modelType = Note_1.default.modelType();
        }
        if (options.format && options.format === 'json') {
            this.stdout(JSON.stringify(items));
        }
        else {
            let hasTodos = false;
            for (let i = 0; i < items.length; i++) {
                const item = items[i];
                if (item.is_todo) {
                    hasTodos = true;
                    break;
                }
            }
            const seenTitles = [];
            const rows = [];
            let shortIdShown = false;
            for (let i = 0; i < items.length; i++) {
                const item = items[i];
                const row = [];
                if (options.long) {
                    row.push(BaseModel_1.default.shortId(item.id));
                    shortIdShown = true;
                    if (modelType === Folder_1.default.modelType()) {
                        row.push(await Folder_1.default.noteCount(item.id));
                    }
                    row.push(time_1.default.formatMsToLocal(item.user_updated_time));
                }
                let title = item.title;
                if (!shortIdShown && (seenTitles.indexOf(item.title) >= 0 || !item.title)) {
                    title += ` (${BaseModel_1.default.shortId(item.id)})`;
                }
                else {
                    seenTitles.push(item.title);
                }
                if (hasTodos) {
                    if (item.is_todo) {
                        row.push(sprintf('[%s]', item.todo_completed ? 'X' : ' '));
                    }
                    else {
                        row.push('   ');
                    }
                }
                row.push(title);
                rows.push(row);
            }
            cliUtils.printArray(this.stdout.bind(this), rows);
        }
    }
}
module.exports = Command;
//# sourceMappingURL=command-ls.js.map