/*
 * 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.
 */

"use strict";

/**
 * This module provides a interface to access persistent preferences for this plug-in.
 */

var Q         = require("q"),
    PLUGINID  = require("../package.json").name,
    JSXRunner = require("../JSXRunner");

var _generator,
    _preferences = {};

/**
 * Returns the value of the preference with the given key.
 *
 * @param {!string} preference key to look up
 * @return {*} value of request preference
 */
function getPref(key) {
    if (key && _preferences) {
        return _preferences[key];
    }
}

/**
 * Imported from Generator.
 */
function escapePluginId(pluginId) {
    if (!pluginId) { return pluginId; }
    return pluginId.replace(/[^a-zA-Z0-9]/g, function (char) {
        return "_" + char.charCodeAt(0) + "_";
    });
}



/**
 * Sets a preference value with the given key.
 *
 * @param {!string} preference key to set
 * @param {*} value of preference to set
 */
function setPref(key, value) {
    _preferences[key] = value;
    var pluginKey = escapePluginId(PLUGINID),
        stringifiedSettings;

    stringifiedSettings = JSON.stringify(_preferences);

    var params = {
        key: pluginKey,
        settings: stringifiedSettings,
        persistent: true
    };

    JSXRunner.runJSX("setCustomOptions", params);
}

/**
 * Initializes preferences
 *
 * @param {!Generator} PS Generator-core
 * @return {Promise} promise resolved when the persisted preferences have been read
 */
function init(generator) {
    var deferred = Q.defer();
    _generator = generator;

    _generator.getCustomOptions(PLUGINID).then(function(settings) {
        _preferences = settings;
        deferred.resolve();
    });

    return deferred.promise;
}

// exported symbols
exports.getPref = getPref;
exports.setPref = setPref;
exports.init    = init;
