import path from 'path';
import {readFileSync, writeFileSync} from 'fs';
import {Logger} from '../logging/logger.js';

export default class JsonManager {

    /**
     * Read the current data in a file
     * @param {*} filePath 
     * @returns deserialized content
     */
    static read(filePath) {
        try {
            const fullPath = path.resolve(filePath);
            const jsonString = readFileSync(fullPath, 'utf8');

            return JSON.parse(jsonString);
        } catch (err) {
            Logger.error('Error reading JSON file: ', err.message);
            return null;
        }
    }

    /**
     * Write the given data in a file by overriding the previous data 
     * @param {*} filePath 
     * @param {*} data
     * @returns 
     */
    static writeUnsafe(filePath, data) {
        try {
            const fullPath = path.resolve(filePath);
            
            const jsonString = JSON.stringify(data);

            writeFileSync(fullPath, jsonString, 'utf8', async err =>  {
                if(err) await Logger.error(err.message);
            });

        } catch (err) {
            Logger.error('Error writting in JSON file: ', err.message);
            return null;
        }
    }

    static upsertToken(filePath, userData) {
        const existingData = JsonManager.read(filePath);

        const index = existingData.findIndex(e => e.userId === userData.userId);

        if (index !== -1) {
            existingData.splice(index, 1, userData);
        } else {
            existingData.push(userData);
        }

        JsonManager.writeUnsafe(filePath, existingData);
        return existingData;
    }

    static upsertPost(filePath, { userId, permalink }) {
        const data = JsonManager.read(filePath);
        let modified = false;

        const index = data.findIndex(e => e.userId === userId);

        if (index !== -1) {
            if (data[index].permalink !== permalink) {
                data[index].permalink = permalink;
                modified = true;
            }
        } else {
            data.push({ userId, permalink });
            modified = true;
        }

        if (modified) {
            JsonManager.writeUnsafe(filePath, data);
        }

        return modified;
    }
}

