"use strict";

const fs   = require('fs');
const path = require('path');

function PluginStorage(paths){
    function fileFor(id){ return path.join(paths.pluginData(id), 'config.json'); }
    function read(id){
        try { return JSON.parse(fs.readFileSync(fileFor(id), 'utf8')); }
        catch (e) { if (e.code === 'ENOENT') return {}; throw e; }
    }
    function write(id, data){
        var file = fileFor(id);
        var tmp  = file + '.tmp';

        fs.mkdirSync(path.dirname(file), { recursive: true });
        fs.writeFileSync(tmp, JSON.stringify(data, null, 2), 'utf8');
        fs.renameSync(tmp, file);
    }

    this.get = function(id, key){ return read(id)[key]; };
    this.set = function(id, key, value){
        var data = read(id);

        data[key] = value;
        write(id, data);
        return value;
    };
    this.tempPath = function(id){
        var dir = path.join(paths.pluginData(id), 'tmp');

        fs.mkdirSync(dir, { recursive: true });
        return dir;
    };
}

module.exports = PluginStorage;
