<?php declare(strict_types=1);
/**
 * Banker
 *
 * A Caching library implementing psr/cache
 *
 * PHP version 7.0
 *
 * @package     Banker
 * @author      Timothy J. Warren <tim@timshomepage.net>
 * @copyright   2016 - 2017  Timothy J. Warren
 * @license     http://www.opensource.org/licenses/mit-license.html  MIT License
 * @version     1.0.1
 * @link        https://git.timshomepage.net/timw4mail/banker
 */
namespace Aviat\Banker\Tests;

use Aviat\Banker\{Item, ItemCollection, Pool};
use Aviat\Banker\Exception\InvalidArgumentException;
use Monolog\Logger;
use Monolog\Handler\SyslogHandler;
use PHPUnit\Framework\TestCase;
use Psr\Log\{LoggerInterface, NullLogger};

class PoolTest extends TestCase {
	
	protected $pool;
	
	public function setUp()
	{
		$this->pool = new Pool([
			'driver' => 'null',
			'connection' => []
		]);
	}
	
	public function testGetDefaultLogger()
	{
		$friend = new Friend($this->pool);
		$driverFriend = new Friend($friend->driver);
		
		// Check that a valid logger is set
		$this->assertInstanceOf(LoggerInterface::class, $friend->getLogger(), "Logger exists after being set");
		$this->assertInstanceOf(LoggerInterface::class, $driverFriend->getLogger(), "Logger exists on driver after being set");
		
		// Make sure we get the default Null logger
		$this->assertTrue(is_a($friend->getLogger(), NullLogger::class));
		$this->assertTrue(is_a($driverFriend->getLogger(), NullLogger::class));
	}
	
	public function testSetLoggerInConstructor()
	{
		$logger = new Logger('test');
		$logger->pushHandler(new SyslogHandler(Logger::WARNING));
		
		$pool = new Pool([
			'driver' => 'null',
			'connection' => [],
		], $logger);
		
		$friend = new Friend($pool);
		$driverFriend = new Friend($friend->driver);
		
		// Check that a valid logger is set
		$this->assertInstanceOf(LoggerInterface::class, $friend->getLogger(), "Logger exists after being set");
		$this->assertInstanceOf(LoggerInterface::class, $driverFriend->getLogger(), "Logger exists on driver after being set");
		
		// Make sure we aren't just getting the default Null logger
		$this->assertFalse(is_a($friend->getLogger(), NullLogger::class));
		$this->assertFalse(is_a($driverFriend->getLogger(), NullLogger::class));
	}
	
	public function testGetSetLogger()
	{
		$logger = new Logger('test');
		$logger->pushHandler(new SyslogHandler(Logger::WARNING));
		
		$this->pool->setLogger($logger);
		
		$friend = new Friend($this->pool);
		$driverFriend = new Friend($friend->driver);
		
		// Check that a valid logger is set
		$this->assertInstanceOf(LoggerInterface::class, $friend->getLogger(), "Logger exists after being set");
		$this->assertInstanceOf(LoggerInterface::class, $driverFriend->getLogger(), "Logger exists on driver after being set");
		
		// Make sure we aren't just getting the default Null logger
		$this->assertFalse(is_a($friend->getLogger(), NullLogger::class));
		$this->assertFalse(is_a($driverFriend->getLogger(), NullLogger::class));
	}

	public function testGetItem()
	{
		$item = $this->pool->getItem('foo');
		$this->assertInstanceOf(Item::class, $item);
	}
	
	public function testItemBadKey()
	{
		$this->expectException(InvalidArgumentException::class);
		$this->expectExceptionMessage("Cache key must be a string.");
		
		$this->pool->getItem([]);
	}
	
	public function testGetItems()
	{
		$collection = $this->pool->getItems(['foo', 'bar', 'baz']);
		$this->assertInstanceOf(ItemCollection::class, $collection);
		
		foreach($collection as $item)
		{
			$this->assertInstanceOf(Item::class, $item);
		}
	}
	
	public function testEmptyGetItems()
	{
		$collection = $this->pool->getItems();
		
		$this->assertInstanceOf(ItemCollection::class, $collection);
		$this->assertEquals(0, count($collection));
	}
	
	public function testHasItem()
	{
		// The key doesn't exist yet
		$this->assertFalse($this->pool->hasItem('foobar'));
		
		// Create the item
		$item = $this->pool->getItem('foobar')
			->set('baz')
			->save();
		
		// The item exists now
		$this->assertTrue($this->pool->hasItem('foobar'));
	}
	
	public function testHasItemBadKey()
	{
		$this->expectException(InvalidArgumentException::class);
		$this->expectExceptionMessage("Cache key must be a string.");
		
		$this->pool->hasItem(34);
	}
	
	public function testClear()
	{
		// Call clear to make sure we are working from a clean slate to start
		$this->pool->clear();
		
		$data = [
			'foo' => 'bar',
			'bar' => 'baz',
			'foobar' => 'foobarbaz'
		];
		
		// Set up some data
		$this->setupDataInCache($data);
		
		foreach($data as $key => $val)
		{
			$this->assertTrue($this->pool->hasItem($key));
			$item = $this->pool->getItem($key);
			$this->assertEquals($val, $item->get());
		}
		
		// Now we clear it all!
		$this->pool->clear();
		
		foreach($data as $key => $val)
		{
			$this->assertFalse($this->pool->hasItem($key));
			$item = $this->pool->getItem($key);
			$this->assertNull($item->get());
		}
	}
	
	public function testDeleteItemBadKey()
	{
		$this->expectException(InvalidArgumentException::class);
		$this->expectExceptionMessage("Cache key must be a string.");
		
		$this->pool->deleteItem(34);
	}
	
	public function testDeleteItemThatDoesNotExist()
	{
		$this->pool->clear();
		$this->assertFalse($this->pool->deleteItem('foo'));
	}
	
	public function testDeleteItem()
	{
		// Start with a clean slate
		$this->pool->clear();
		
		$data = [
			'foo' => 'bar',
			'bar' => 'baz',
			'foobar' => 'foobarbaz'
		];
		
		$this->setupDataInCache($data);
		
		$this->pool->deleteItem('foo');
		
		// The item no longer exists
		$this->assertFalse($this->pool->hasItem('foo'));
		$item = $this->pool->getItem('foo');
		$this->assertNull($item->get());
		
		// The other items still exist
		foreach(['bar', 'foobar'] as $key)
		{
			$this->assertTrue($this->pool->hasItem($key));
			$item = $this->pool->getItem($key);
			$this->assertFalse(is_null($item->get()));
		}
	}
	
	public function testDeleteItems()
	{
		$this->pool->clear();
		
		$data = [
			'foo' => 'bar',
			'bar' => 'baz',
			'foobar' => 'foobarbaz'
		];
		
		$this->setupDataInCache($data);
		
		$this->pool->deleteItems(['foo', 'bar']);
		
		foreach(['foo', 'bar'] as $key)
		{
			$this->assertFalse($this->pool->hasItem($key));
			$item = $this->pool->getItem($key);
			$this->assertNull($item->get());
		}
	}
	
	public function testSaveDeferred()
	{
		$this->pool->clear();
		
		$data = [
			'foo' => 'bar',
			'bar' => 'baz',
			'foobar' => 'foobarbaz'
		];
		
		$this->setupDeferredData($data);
		
		// See that the data is returned by the pool
		foreach($data as $key => $val)
		{
			$this->assertTrue($this->pool->hasItem($key));
			$item = $this->pool->getItem($key);
			
			// The cache hasn't been updated yet, even
			// though the pool data has
			$this->assertNotEquals($data[$key], $item->get());
		}
	}
	
	public function testCommit()
	{
		$this->pool->clear();
		
		// If there are no deferred items, this will return true
		$this->assertTrue($this->pool->commit());
		
		$data = [
			'foo' => 'bar',
			'bar' => 'baz',
			'foobar' => 'foobarbaz'
		];
		
		$this->setupDeferredData($data);
		
		// See that the data is returned by the pool
		foreach($this->pool->getItems(array_keys($data)) as $key => $item)
		{
			$this->assertTrue($this->pool->hasItem($key));
			
			// The cache hasn't been updated yet, even
			// though the pool data has
			$this->assertNotEquals($data[$key], $item->get());
		}
		
		$this->pool->commit();
		
		// See that the data is saved in the cache backend
		foreach($this->pool->getItems(array_keys($data)) as $key => $item)
		{
			$this->assertTrue($this->pool->hasItem($key));
			$this->assertEquals($data[$key], $item->get());
		}
	}
	
	protected function setupDeferredData($data)
	{
		foreach($data as $key => $val)
		{
			$item = $this->pool->getItem($key)
				->set($val);
				
			$this->assertTrue($this->pool->saveDeferred($item));
		}
	}
	
	protected function setupDataInCache($data)
	{
		foreach($data as $key => $val)
		{
			$item = $this->pool->getItem($key)
				->set($val);
				
			$this->pool->save($item);
		}
	}
}