import test from 'ava';
import tk from 'timekeeper';
import keyvTestSuite from '@keyv/test-suite';
import Keyv from 'this';

test.serial('Keyv is a class', t => {
	t.is(typeof Keyv, 'function');
	t.throws(() => Keyv()); // eslint-disable-line new-cap
	t.notThrows(() => new Keyv());
});

test.serial('Keyv accepts storage adapters', async t => {
	const store = new Map();
	const keyv = new Keyv({ store });
	t.is(store.size, 0);
	await keyv.set('foo', 'bar');
	t.is(await keyv.get('foo'), 'bar');
	t.is(store.size, 1);
});

test.serial('Keyv hands tll functionality over to ttl supporting stores', async t => {
	t.plan(3);
	const store = new Map();
	store.ttlSupport = true;
	const storeSet = store.set;
	store.set = (key, val, ttl) => {
		t.is(ttl, 100);
		storeSet.call(store, key, val, ttl);
	};
	const keyv = new Keyv({ store });
	await keyv.set('foo', 'bar', 100);
	t.is(await keyv.get('foo'), 'bar');
	tk.freeze(Date.now() + 150);
	t.is(await keyv.get('foo'), 'bar');
	tk.reset();
});

test.serial('Keyv respects default tll option', async t => {
	const store = new Map();
	const keyv = new Keyv({ store, ttl: 100 });
	await keyv.set('foo', 'bar');
	t.is(await keyv.get('foo'), 'bar');
	tk.freeze(Date.now() + 150);
	t.is(await keyv.get('foo'), undefined);
	tk.reset();
});

test.serial('.set(key, val, ttl) overwrites default tll option', async t => {
	const startTime = Date.now();
	tk.freeze(startTime);
	const store = new Map();
	const keyv = new Keyv({ store, ttl: 200 });
	await keyv.set('foo', 'bar');
	await keyv.set('fizz', 'buzz', 100);
	await keyv.set('ping', 'pong', 300);
	t.is(await keyv.get('foo'), 'bar');
	t.is(await keyv.get('fizz'), 'buzz');
	t.is(await keyv.get('ping'), 'pong');
	tk.freeze(startTime + 150);
	t.is(await keyv.get('foo'), 'bar');
	t.is(await keyv.get('fizz'), undefined);
	t.is(await keyv.get('ping'), 'pong');
	tk.freeze(startTime + 250);
	t.is(await keyv.get('foo'), undefined);
	t.is(await keyv.get('ping'), 'pong');
	tk.freeze(startTime + 350);
	t.is(await keyv.get('ping'), undefined);
	tk.reset();
});

test.serial('.set(key, val, ttl) where ttl is "0" overwrites default tll option and sets key to never expire', async t => {
	const startTime = Date.now();
	tk.freeze(startTime);
	const store = new Map();
	const keyv = new Keyv({ store, ttl: 200 });
	await keyv.set('foo', 'bar', 0);
	t.is(await keyv.get('foo'), 'bar');
	tk.freeze(startTime + 250);
	t.is(await keyv.get('foo'), 'bar');
	tk.reset();
});

const store = () => new Map();
keyvTestSuite(test, Keyv, store);

@@ -539,54 +539,26 @@
 eyv 
-hand
+passe
 s tll 
-functionality over to ttl supporting
+info to
  sto
@@ -584,17 +584,17 @@
 %09t.plan(
-3
+1
 );%0A%09cons
@@ -618,34 +618,8 @@
 ();%0A
-%09store.ttlSupport = true;%0A
 %09con
@@ -813,125 +813,8 @@
 0);%0A
-%09t.is(await keyv.get('foo'), 'bar');%0A%09tk.freeze(Date.now() + 150);%0A%09t.is(await keyv.get('foo'), 'bar');%0A%09tk.reset();%0A
 %7D);%0A

Update TTL store test to reflect new behaviour