<?php

/**
 * Copyright 2014 Fabian Grutschus. All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without modification,
 * are permitted provided that the following conditions are met:
 *
 * 1. Redistributions of source code must retain the above copyright notice, this
 *   list of conditions and the following disclaimer.
 *
 * 2. Redistributions in binary form must reproduce the above copyright notice,
 *   this list of conditions and the following disclaimer in the documentation
 *   and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
 * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 * The views and conclusions contained in the software and documentation are those
 * of the authors and should not be interpreted as representing official policies,
 * either expressed or implied, of the copyright holders.
 *
 * @author    Fabian Grutschus <f.grutschus@lubyte.de>
 * @copyright 2014 Fabian Grutschus. All rights reserved.
 * @license   BSD
 * @link      http://github.com/fabiang/xmpp
 */

namespace Fabiang\Xmpp\Connection;

use PHPUnit\Framework\TestCase;
use Fabiang\Xmpp\Stream\XMLStream;
use Fabiang\Xmpp\Stream\SocketClient;
use Fabiang\Xmpp\EventListener\Stream\Stream;
use Fabiang\Xmpp\Event\EventManager;
use Fabiang\Xmpp\Event\Event;
use Fabiang\Xmpp\Options;
use Psr\Log\LogLevel;

/**
 * Generated by PHPUnit_SkeletonGenerator 1.2.1 on 2014-01-03 at 01:02:08.
 *
 * @coversDefaultClass Fabiang\Xmpp\Connection\Socket
 */
class SocketTest extends TestCase
{

    /**
     * @var Socket
     */
    protected $object;

    /**
     * Sets up the fixture, for example, opens a network connection.
     * This method is called before a test is executed.
     *
     * @return void
     */
    protected function setUp()
    {
        $mock = $this->getMockBuilder('\Fabiang\Xmpp\Stream\SocketClient')
            ->setConstructorArgs(array('tcp://localhost:9999'))
            ->setMethods(array('read', 'write', 'connect', 'close', 'setBlocking'))
            ->getMock();

        $this->object = new Socket($mock);
        $this->object->setOptions(new Options('tcp://localhost:9999'));
    }

    /**
     * Test constructor.
     *
     * @covers ::__construct
     * @uses Fabiang\Xmpp\Connection\AbstractConnection
     * @uses Fabiang\Xmpp\Connection\Socket::setSocket
     * @uses Fabiang\Xmpp\Connection\Socket::getSocket
     * @uses Fabiang\Xmpp\Stream\SocketClient
     * @uses Fabiang\Xmpp\Options
     * @return void
     */
    public function testConstructor()
    {
        $mock   = $this->createMock(SocketClient::class);
        $object = new Socket($mock, '');
        $this->assertSame($mock, $object->getSocket());
    }

    /**
     * Test receivding data.
     *
     * @covers ::receive
     * @uses Fabiang\Xmpp\Connection\Socket::__construct
     * @uses Fabiang\Xmpp\Connection\Socket::setSocket
     * @uses Fabiang\Xmpp\Stream\SocketClient
     * @uses Fabiang\Xmpp\Connection\AbstractConnection
     * @uses Fabiang\Xmpp\Connection\Socket::getAddress
     * @uses Fabiang\Xmpp\Connection\Socket::getSocket
     * @uses Fabiang\Xmpp\Stream\SocketClient
     * @uses Fabiang\Xmpp\Connection\AbstractConnection
     * @uses Fabiang\Xmpp\Stream\XMLStream
     * @uses Fabiang\Xmpp\Event\XMLEvent
     * @uses Fabiang\Xmpp\Util\XML
     * @uses Fabiang\Xmpp\Options
     * @uses Fabiang\Xmpp\Event\EventManager
     * @return void
     */
    public function testReceive()
    {
        $return = '<xml xmlns="test"></xml>';
        $mock   = $this->object->getSocket();
        $mock->expects($this->once())
            ->method('read')
            ->with($this->equalTo(4096))
            ->will($this->returnValue($return));
        $this->assertSame($return, $this->object->receive());
    }

    /**
     * Test sending data.
     *
     * @covers ::send
     * @uses Fabiang\Xmpp\Connection\Socket::__construct
     * @uses Fabiang\Xmpp\Connection\Socket::setSocket
     * @uses Fabiang\Xmpp\Connection\Socket::connect
     * @uses Fabiang\Xmpp\Connection\Socket::getAddress
     * @uses Fabiang\Xmpp\Connection\Socket::getSocket
     * @uses Fabiang\Xmpp\Stream\SocketClient
     * @uses Fabiang\Xmpp\Connection\AbstractConnection
     * @uses Fabiang\Xmpp\Stream\XMLStream
     * @uses Fabiang\Xmpp\Event\XMLEvent
     * @uses Fabiang\Xmpp\Util\XML
     * @uses Fabiang\Xmpp\Options
     * @uses Fabiang\Xmpp\Event\EventManager
     * @return void
     */
    public function testSend()
    {
        $data = '<xml xmlns="test"></xml>';

        $mock = $this->object->getSocket();
        $mock->expects($this->at(0))
            ->method('write');

        $mock->expects($this->at(3))
            ->method('write')
            ->with($this->equalTo($data));

        $this->object->send($data);
        $this->assertTrue($this->object->isConnected());
    }

    /**
     * Test connecting.
     *
     * @covers ::connect
     * @covers ::isConnected
     * @uses Fabiang\Xmpp\Connection\Socket::__construct
     * @uses Fabiang\Xmpp\Connection\Socket::setSocket
     * @uses Fabiang\Xmpp\Connection\Socket::send
     * @uses Fabiang\Xmpp\Connection\Socket::getAddress
     * @uses Fabiang\Xmpp\Connection\Socket::getSocket
     * @uses Fabiang\Xmpp\Stream\SocketClient
     * @uses Fabiang\Xmpp\Connection\AbstractConnection
     * @uses Fabiang\Xmpp\Stream\XMLStream
     * @uses Fabiang\Xmpp\Event\XMLEvent
     * @uses Fabiang\Xmpp\Util\XML
     * @uses Fabiang\Xmpp\Options
     * @uses Fabiang\Xmpp\Event\EventManager
     * @return void
     */
    public function testConnect()
    {
        $mock = $this->object->getSocket();
        $mock->expects($this->once())
            ->method('connect');
        $this->object->connect();
        $this->assertTrue($this->object->isConnected());
    }

    /**
     * Test logging of events.
     *
     * @covers ::log
     * @covers ::getAddress
     * @uses Fabiang\Xmpp\Connection\Socket::__construct
     * @uses Fabiang\Xmpp\Connection\Socket::setSocket
     * @uses Fabiang\Xmpp\Connection\Socket::send
     * @uses Fabiang\Xmpp\Connection\Socket::connect
     * @uses Fabiang\Xmpp\Connection\Socket::getSocket
     * @uses Fabiang\Xmpp\Stream\SocketClient
     * @uses Fabiang\Xmpp\Connection\AbstractConnection
     * @uses Fabiang\Xmpp\Stream\XMLStream
     * @uses Fabiang\Xmpp\Options
     * @uses Fabiang\Xmpp\Event\EventManager
     * @uses Fabiang\Xmpp\Util\XML
     * @uses Fabiang\Xmpp\Event\Event
     * @uses Fabiang\Xmpp\Event\XMLEvent
     * @return void
     */
    public function testLogging()
    {
        /* @var $event Event */
        $events = array();
        $this->object->getEventManager()->attach('logger', function (Event $eventObject) use(&$events) {
            $events[] = $eventObject;
        });

        $mock = $this->object->getSocket();
        $mock->expects($this->once())
            ->method('connect');

        $this->object->connect();

        $this->assertInstanceOf('\\Fabiang\\Xmpp\\Event\\Event', $events[0]);
        $parameters = $events[0]->getParameters();
        $this->assertSame("Connected to 'tcp://localhost:9999'", $parameters[0]);
        $this->assertSame(LogLevel::DEBUG, $parameters[1]);
    }

    /**
     * Test reseting streams.
     *
     * @covers ::resetStreams
     * @uses Fabiang\Xmpp\Connection\Socket::__construct
     * @uses Fabiang\Xmpp\Connection\Socket::setSocket
     * @uses Fabiang\Xmpp\Stream\SocketClient
     * @uses Fabiang\Xmpp\Connection\AbstractConnection
     * @uses Fabiang\Xmpp\Stream\XMLStream
     * @uses Fabiang\Xmpp\Options
     * @uses Fabiang\Xmpp\Stream\XMLStream
     * @return void
     */
    public function testResetStreams()
    {
        $oldInput  = $this->object->getInputStream()->getParser();
        $oldOutput = $this->object->getOutputStream()->getParser();

        $this->object->resetStreams();

        $this->assertNotSame($oldInput, $this->object->getInputStream()->getParser());
        $this->assertNotSame($oldOutput, $this->object->getOutputStream()->getParser());
    }

    /**
     * Test disconnecting.
     *
     * @covers ::disconnect
     * @covers ::isConnected
     * @uses Fabiang\Xmpp\Connection\Socket::__construct
     * @uses Fabiang\Xmpp\Connection\Socket::setSocket
     * @uses Fabiang\Xmpp\Connection\Socket::send
     * @uses Fabiang\Xmpp\Connection\Socket::connect
     * @uses Fabiang\Xmpp\Connection\Socket::getAddress
     * @uses Fabiang\Xmpp\Connection\Socket::getSocket
     * @uses Fabiang\Xmpp\Stream\SocketClient
     * @uses Fabiang\Xmpp\Connection\AbstractConnection
     * @uses Fabiang\Xmpp\Event\XMLEvent
     * @uses Fabiang\Xmpp\Event\EventManager
     * @uses Fabiang\Xmpp\Stream\XMLStream
     * @uses Fabiang\Xmpp\Options
     * @uses Fabiang\Xmpp\Util\XML
     * @return void
     */
    public function testDisconnect()
    {
        $mock = $this->object->getSocket();
        $mock->expects($this->any())
            ->method('write');
        $mock->expects($this->once())
            ->method('connect');
        $mock->expects($this->once())
            ->method('close');

        $this->object->connect();
        $this->assertTrue($this->object->isConnected());

        $this->object->disconnect();
        $this->assertFalse($this->object->isConnected());
    }

    /**
     * @covers ::getSocket
     * @covers ::setSocket
     * @uses Fabiang\Xmpp\Connection\Socket::__construct
     * @uses Fabiang\Xmpp\Stream\SocketClient
     * @uses Fabiang\Xmpp\Connection\AbstractConnection
     * @uses Fabiang\Xmpp\Options
     * @return void
     */
    public function testSetAndGetSocket()
    {
        $socket = new SocketClient('tcp://localhost:9999');
        $this->assertSame($socket, $this->object->setSocket($socket)->getSocket());
    }

    /**
     * Test adding listeners.
     *
     * @covers ::addListener
     * @covers ::getListeners
     * @uses Fabiang\Xmpp\Connection\Socket::__construct
     * @uses Fabiang\Xmpp\Connection\Socket::setSocket
     * @uses Fabiang\Xmpp\Stream\SocketClient
     * @uses Fabiang\Xmpp\Connection\AbstractConnection
     * @uses Fabiang\Xmpp\Options
     * @return void
     */
    public function testAddListener()
    {
        $eventListener = new Stream;
        $this->object->addListener($eventListener);
        $this->assertSame(array($eventListener), $this->object->getListeners());
    }

    /**
     * Test setting and getting output stream.
     *
     * @covers ::getOutputStream
     * @covers ::setOutputStream
     * @uses Fabiang\Xmpp\Connection\Socket::__construct
     * @uses Fabiang\Xmpp\Connection\Socket::setSocket
     * @uses Fabiang\Xmpp\Stream\SocketClient
     * @uses Fabiang\Xmpp\Connection\AbstractConnection
     * @uses Fabiang\Xmpp\Stream\XMLStream
     * @uses Fabiang\Xmpp\Options
     * @return void
     */
    public function testGetAndSetOutputStream()
    {
        $this->assertInstanceOf('\Fabiang\Xmpp\Stream\XMLStream', $this->object->getOutputStream());
        $outputStream = new XMLStream;
        $this->assertSame($outputStream, $this->object->setOutputStream($outputStream)->getOutputStream());
    }

    /**
     * Test setting and getting input stream.
     *
     * @covers ::getInputStream
     * @covers ::setInputStream
     * @uses Fabiang\Xmpp\Connection\Socket::__construct
     * @uses Fabiang\Xmpp\Connection\Socket::setSocket
     * @uses Fabiang\Xmpp\Stream\SocketClient
     * @uses Fabiang\Xmpp\Connection\AbstractConnection
     * @uses Fabiang\Xmpp\Stream\XMLStream
     * @uses Fabiang\Xmpp\Options
     * @return void
     */
    public function testGetAndSetInputStream()
    {
        $this->assertInstanceOf('\Fabiang\Xmpp\Stream\XMLStream', $this->object->getInputStream());
        $inputStream = new XMLStream;
        $this->assertSame($inputStream, $this->object->setInputStream($inputStream)->getInputStream());
    }

    /**
     * Test setting and getting event manager.
     *
     * @covers ::getEventManager
     * @covers ::setEventManager
     * @uses Fabiang\Xmpp\Connection\Socket::__construct
     * @uses Fabiang\Xmpp\Connection\Socket::setSocket
     * @uses Fabiang\Xmpp\Stream\SocketClient
     * @uses Fabiang\Xmpp\Connection\AbstractConnection
     * @uses Fabiang\Xmpp\Event\EventManager
     * @uses Fabiang\Xmpp\Options
     * @return void
     */
    public function testSetAndGetEventManager()
    {
        $this->assertInstanceOf('\Fabiang\Xmpp\Event\EventManager', $this->object->getEventManager());
        $eventManager = new EventManager;
        $this->assertSame($eventManager, $this->object->setEventManager($eventManager)->getEventManager());
    }

    /**
     * Check timeout when not receiving input.
     *
     * @covers ::receive
     * @covers ::checkTimeout
     * @covers ::reconnectTls
     * @uses Fabiang\Xmpp\Connection\Socket::__construct
     * @uses Fabiang\Xmpp\Connection\Socket::send
     * @uses Fabiang\Xmpp\Connection\Socket::connect
     * @uses Fabiang\Xmpp\Connection\Socket::getAddress
     * @uses Fabiang\Xmpp\Connection\Socket::getSocket
     * @uses Fabiang\Xmpp\Connection\Socket::setSocket
     * @uses Fabiang\Xmpp\Stream\SocketClient
     * @uses Fabiang\Xmpp\Connection\AbstractConnection
     * @uses Fabiang\Xmpp\Event\EventManager
     * @uses Fabiang\Xmpp\Options
     * @uses Fabiang\Xmpp\Stream\XMLStream
     * @uses Fabiang\Xmpp\Event\Event
     * @uses Fabiang\Xmpp\Event\XMLEvent
     * @uses Fabiang\Xmpp\Util\XML
     * @expectedException \Fabiang\Xmpp\Exception\TimeoutException
     * @expectedExceptionMessage Connection lost after 0 seconds
     * @medium
     * @return void
     */
    public function testReceiveWithTimeout()
    {
        $mock = $this->object->getSocket();
        $mock->expects($this->exactly(2))
            ->method('write');
        $mock->expects($this->exactly(3))
            ->method('connect');
        $mock->expects($this->exactly(1))
            ->method('close');

        $this->object->getOptions()->setTimeout(0);
        $this->object->connect();
        $this->assertSame('tcp://localhost:9999', $this->object->getOptions()->getAddress());
        $this->assertSame('tcp://localhost:9999', $this->object->getSocket()->getAddress());
        $this->object->receive();
        $this->assertSame('tls://localhost:9999', $this->object->getOptions()->getAddress());
        $this->assertSame('tls://localhost:9999', $this->object->getSocket()->getAddress());
        $this->object->receive();
    }

}
