/*
 * ADOBE CONFIDENTIAL
 *
 * Copyright (c) 2015 Adobe Systems Incorporated. All rights reserved.
 *
 * NOTICE:  All information contained herein is, and remains
 * the property of Adobe Systems Incorporated and its suppliers,
 * if any.  The intellectual and technical concepts contained
 * herein are proprietary to Adobe Systems Incorporated and its
 * suppliers and are protected by trade secret or copyright law.
 * Dissemination of this information or reproduction of this material
 * is strictly forbidden unless prior written permission is obtained
 * from Adobe Systems Incorporated.
 */

/*jslint vars: true, plusplus: true, devel: true, nomen: true, indent: 4, bitwise: true, node:true */
/*global require: true, $: true, exports: true, csInterface: true*/

//FIXME? this could potentially use the in memory interface
(function () {
    "use strict";
    var fs = require("fs"),
        _  = require("underscore"),
        PathUtils = require("../PathUtils"),
        
        settings,
        canWriteFile = true,
        loadFile = function() {
        if(settings) {
            return;
        }
        var fileContents = "{}";
        try {
            fileContents = fs.readFileSync(PathUtils.getUserSettingPath(), "utf8");
            canWriteFile = true;
        } catch (e) {
            if (e.code !== 'ENOENT') throw e;
            //open and close it, we just want to make sure we have it. Nothing more
            fileContents = _createSettingFile(PathUtils.getUserSettingPath());
        }
        try {
            settings = JSON.parse(fileContents);
        } catch(e) {
            settings = {};
        }
    },
    _createSettingFile = function(settingPath) {
        try {
            fs.closeSync(fs.openSync(settingPath, "w+"));
        } catch(e) {
            canWriteFile = false;
            console.warn("user settings file could not be created");
        }
        return "{}";
    },
    //has to be late binding of the value for testing :(
    writeSettings = _.compose(function(value) {
        if(!canWriteFile) { return; }
        try {
            fs.writeFileSync(PathUtils.getUserSettingPath(), value);
        } catch(e) {
            console.warn("could not write to user settings file");
        }
    }, JSON.stringify),
    setSettings = _.compose(writeSettings, function(setting) {
        if(!settings) {
            settings = {};
        }
        _.extend(settings, setting);
        return settings;
    }),
    deleteSetting = _.compose(writeSettings, function(key) {
        loadFile();
        delete settings[key];
        return settings;
    });
    module.exports = {
        set: setSettings,
        get: function(key) {
            loadFile();
            return settings[key];
        },
        deleteSetting: deleteSetting
    };
})();
