"use strict";

const jetpack = require('fs-jetpack');
const extend = require('extend');

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

const DEFAULT_OPTIONS = {
	'cacheDir': process.cwd() + '/cache',
	'cacheExpire': 3600 * 1000, // 1hr
	'prefix': 'cs',
	'fixCacheExpire': false,
	'rejectOnNull': false
};

let FileCacheSimple = function(options) {
	this._options = (options) ? extend(true, DEFAULT_OPTIONS, options) : DEFAULT_OPTIONS;
	this._fs = jetpack.cwd(this._options.cacheDir);
};

FileCacheSimple.prototype.set = function(key, value, fixCacheExpire) {
	let cacheFile = util.format('%s.%s.json', this._options.prefix, key);
	let cacheObj = {
		'cachedOn': (new Date()).toISOString(),
		'content': value
	};
	if(this._options.fixCacheExpire || fixCacheExpire)
		cacheObj.cacheExpire = (fixCacheExpire) ? fixCacheExpire : this._options.cacheExpire;
	this._fs.writeAsync(cacheFile, cacheObj);
};

FileCacheSimple.prototype.get = function(key) {
	let self = this;
	return new Promise(function(resolve, reject) {
		let cacheFile = util.format('%s.%s.json', self._options.prefix, key);
		self._fs.readAsync(cacheFile, 'jsonWithDates')
			.then(function(cache) {
				if(!cache || cache === null) {
					if(self._options.rejectOnNull)
						return reject();
					return resolve(null);
				}

				let currentTime = (new Date()).getTime();
				let cacheExpire = (cache.cacheExpire) ? cache.cacheExpire : self._options.cacheExpire;
				if(currentTime - cache.cachedOn >= cacheExpire) {
					return resolve(null);
				}
				return resolve(cache.content);
			})
			.catch(reject);
	});
};

FileCacheSimple.prototype.remove = function(key) {
	let cacheFile = util.format('%s.%s.json', this._options.prefix, key);
	this._fs.remove(cacheFile);
};

exports = module.exports = FileCacheSimple;

@@ -887,24 +887,31 @@
 heExpire;%0D%0A%09
+return 
 this._fs.wri
@@ -1774,24 +1774,31 @@
 ix, key);%0D%0A%09
+return 
 this._fs.rem
@@ -1800,16 +1800,21 @@
 s.remove
+Async
 (cacheFi

Return promises on remove and write