//=============================================================================
// CommonSave.js
//=============================================================================


/*:ja
 * @plugindesc 共通セーブ
 * @author Milk Force
 * 
 * @param SaveKey
 * @desc セーブ名
 * @default oppai
 * 
 * @help 
 */

var $common_save=null;

(function(){
	'use strict';
	
	var _DataManager_loadDatabase=DataManager.loadDatabase;
		DataManager.loadDatabase=function(){
		_DataManager_loadDatabase.call(this);
		
		$common_save=new CommonSave();
	};
	
	function CommonSave(){
		this.initialize.apply(this,arguments);
	};
	
	CommonSave.prototype.initialize=function(){
		this._data={};
		this._savekey="";
		
		var parameters = PluginManager.parameters('CommonSave');
		
		if(StorageManager.isLocalMode()){
			this._savekey=StorageManager.localFileDirectoryPath() + String(parameters['SaveKey'] || 'oppai') + '.rpgsave';
		}else{
			this._savekey=String(parameters['SaveKey'] || 'oppai');
		}
		this.data_load();
	};
	
	
	CommonSave.prototype.set = function(name, value) {
        if (name != null) {
        	this._data[name] = value;
        	this.data_save(JSON.stringify(this._data));
        }

    };
	
    CommonSave.prototype.get = function(name) {
        if(this._data.hasOwnProperty(name)){
			if(isFinite(this._data[name])){
				return Number(this._data[name]);
			}else{
            	return this._data[name];
			}
        }else{
			return null;	
		}
    };
	
	CommonSave.prototype.data_load=function(){
		var data;
        try{
            if(StorageManager.isLocalMode()){
				var tmp=null;
                var fs = require('fs');
				
                if(fs.existsSync(this._savekey)){
                   	tmp = fs.readFileSync(this._savekey, { encoding: 'utf8' });
					data= LZString.decompressFromBase64(tmp);
				}
            } else {
                data = LZString.decompressFromBase64(localStorage.getItem(this._savekey));
            }
        } catch(e) {
            console.error(e);
        }
		
        if(data != null){
			this._data=JSON.parse(data);
			
        }else{
			this._data={};	
		}
	};
	
	CommonSave.prototype.data_save=function(){
		try{
			var data=LZString.compressToBase64(JSON.stringify(this._data));
			
			if (StorageManager.isLocalMode()) {
				var fs = require('fs');
				
				var dirPath = StorageManager.localFileDirectoryPath();
				if (!fs.existsSync(dirPath)) {
					fs.mkdirSync(dirPath);
				}
				fs.writeFileSync(this._savekey,data);
			} else {
				localStorage.setItem(this._savekey,data);
			}
		} catch(e) {
            console.error(e);
        }
	};
	
	CommonSave.prototype.data_delete=function(){
		this._data={};
		try{
			if (StorageManager.isLocalMode()) {
				var fs = require('fs');
				if (fs.existsSync(this._savekey)) {
					fs.unlinkSync(this._savekey);
				}
			} else {
				localStorage.removeItem(this._savekey);
			}
			this._data={};
		} catch(e) {
            console.error(e);
        }
	 };
	
})();