// Copyright 2014-2025 Jesper Larsson
//
// This file is part of Klipspringer, <https://klipspringer.avadeaux.net/>
//
// Klipspringer is free software: you can redistribute it and/or modify it under the terms of the
// GNU General Public License as published by the Free Software Foundation, either version 3 of the
// License, or (at your option) any later version.
//
// Klipspringer is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without
// even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// General Public License for more details.
//
// You should have received a copy of the GNU General Public License along with Klipspringer. If
// not, see <https://www.gnu.org/licenses/>.

import * as fs from 'fs';
import * as path from 'path';
import { log } from './log.js';

const maxHistory = 100;

const readHistory = (histFnam) => {
    try {
        return JSON.parse(fs.readFileSync(histFnam))
    } catch (err) {
        if (err.code === 'ENOENT') {
            log.info("Starting new history "+histFnam);
            return [];
        } else if (err instanceof SyntaxError) {
            log.warning("History "+histFnam+" reset due to "+err);
            return [];
        } else {
            throw err;
        }
    }
}

export const history = (histFnam) => {
    const a = readHistory(histFnam);
    const hist = {
        save: () => fs.promises.writeFile(histFnam, JSON.stringify(a))
            .catch(err => { log.error("Error writing history: "+err) }),
        putItem: (item) => {
            const itemIx = a.findIndex(e => e.source == item.source && e.path == item.path);
            if (itemIx >= 0) {  // found, remove from previous position
                a.splice(itemIx, 1);
            }
            if (a.length >= maxHistory) { a.splice(0, a.length-(maxHistory-1)) }
            a.push(item);
            return a.length-1;
        },
        clear: (ix) => {
            a.splice(ix, 1);
        },
        moveToEnd: (ix) => {
            a.push(a.splice(ix, 1)[0]);
            hist.save();
            return a.length-1;
        },
        setPosition: (ix, trackNo, trackTime) => {
            a[ix][2] = trackNo;
            a[ix][3] = trackTime;
        },
        getItem: (ix) => a[ix],
        get length() { return a.length }
    }
    return hist;
}

Version: v4.3.2.2 (2026-05-16T17:03:34+02:00)
Raw file
Source code overview
Klipspringer home