<?php

/*
 * Copyright (c) 2015, Leif Lindbäck
 * 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.
 * 
 * 3. Neither the name of the copyright holder nor the names of its 
 *    contributors may be used to endorse or promote products derived from 
 *    this software without specific prior written permission.
 * 
 * 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 HOLDER 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.
 */

namespace Id1354fw\Core;

use Id1354fw\Util\Classes;

/**
 * @author Leif Lindback, leifl@kth.se
 * 
 * REMEMBER TO START SELENIUM SERVER WITH THE COMMAND selenium-server AT THE BASH SHELL.
 */
class RouterTest extends \PHPUnit_Extensions_Selenium2TestCase {

    const DEF_HANDLER_NAME = 'DefaultRequestHandler';
    const NAMESPACE_NAME = 'Nspart1';
    const NAMESPACE_PART2_NAME = 'Nspart2';
    const CLASS_NAME = 'TestClass1.php';
    const TEST_CLASSES_DIR = '../tests/resources/classes/';
    const MAIN_CLASSES_DIR = '../classes';
    const CLASSPATH_ON_SERVER = '/var/www/html/id1354-fw/classes/';

    private $pathToMainClassesDir;

    protected function setUp() {
        \chdir(self::CLASSPATH_ON_SERVER);
        $this->pathToMainClassesDir = \getcwd();
        $this->recurse_copy(self::TEST_CLASSES_DIR . self::NAMESPACE_NAME, self::NAMESPACE_NAME);
        \copy(self::TEST_CLASSES_DIR . self::CLASS_NAME, self::CLASS_NAME);

        $this->setHost('localhost');
        $this->setPort(4444);
        $this->setBrowser('firefox');
        $this->setBrowserUrl('http://localhost/id1354-fw/');
    }

    private function recurse_copy($src, $dst) {
        $dir = \opendir($src);
        \mkdir($dst);
        while (false !== ( $file = \readdir($dir))) {
            if (( $file != '.' ) && ( $file != '..' )) {
                if (\is_dir($src . '/' . $file)) {
                    $this->recurse_copy($src . '/' . $file, $dst . '/' . $file);
                } else {
                    \copy($src . '/' . $file, $dst . '/' . $file);
                }
            }
        }
        \closedir($dir);
    }

    private function recurse_rmdir($src) {
        $dir = \opendir($src);
        while (false !== ( $file = \readdir($dir))) {
            if (( $file != '.' ) && ( $file != '..' )) {
                $full = $src . '/' . $file;
                if (\is_dir($full)) {
                    $this->recurse_rmdir($full);
                } else {
                    \unlink($full);
                }
            }
        }
        \closedir($dir);
        \rmdir($src);
    }

    protected function tearDown() {
        \chdir($this->pathToMainClassesDir);
        $this->recurse_rmdir(self::NAMESPACE_NAME);
        \unlink(self::CLASS_NAME);
    }

    public function testIndexPhp() {
        $this->nonMatchingAndDefault('index.php');
    }

    public function testInvalidClassName() {
        $this->nonMatchingAndDefault('/indexphp');
        $this->nonMatchingAndDefault('index(php');
        $this->nonMatchingAndDefault('in&dexphp');
        $this->nonMatchingAndDefault('in&dex$php');
        $this->nonMatchingAndDefault('index$php');
//        $this->nonMatchingAndDefault('index#php'); FAILS IN TEST, WORKS IN BROWSER
        $this->nonMatchingAndDefault('indexphp)');
        $this->nonMatchingAndDefault('in//dexphp');
        $this->nonMatchingAndDefault('indexphp');
    }

    public function testMatchingHandler() {
        $this->withMatchingHandler('', 'AMyHandler');
        $this->withMatchingHandler('', 'ZMyHandler');
        $this->withMatchingHandler('Nspart1', 'AMyHandler');
        $this->withMatchingHandler('Nspart1', 'ZMyHandler');
        $this->withMatchingHandler('Nspart1/Nspart2', 'AMyHandler');
        $this->withMatchingHandler('Nspart1/Nspart2', 'ZMyHandler');
    }

    public function testNonMatchingHandler() {
        $this->nonMatchingAndDefault('', 'AMyHandler');
        $this->nonMatchingAndDefault('', 'ZMyHandler');
        $this->nonMatchingAndDefault('Nspart1', 'AMyHandler');
        $this->nonMatchingAndDefault('Nspart1', 'ZMyHandler');
        $this->nonMatchingAndDefault('Nspart1/Nspart2', 'AMyHandler');
        $this->nonMatchingAndDefault('Nspart1/Nspart2', 'ZMyHandler');
    }

    public function testNonMatchingPlainFile() {
        $this->nonMatchingPlainFile('test.html');
        $this->nonMatchingPlainFile('test.php');
        $this->nonMatchingPlainFile('a/test.html');
        $this->nonMatchingPlainFile('/a/test.html');
        $this->nonMatchingPlainFile('a/b/test.html');
    }

    public function testMatchingPlainFile() {
        $this->matchingPlainFile('test.html');
        $this->matchingPlainFile('/test.html');
        $this->matchingPlainFile('tests/test.html');
        $this->matchingPlainFile('/tests/test.html');
        $this->matchingPlainFile('test.php');
    }

    private function matchingPlainFile($url) {
        $filePath = self::CLASSPATH_ON_SERVER . '../' . $url;
        try {
            \touch($filePath);
            $this->url($url);
            $this->assertNotContains('404', $this->source());
        } finally {
            \unlink($filePath);
        }
    }

    private function nonMatchingPlainFile($url) {
        $this->url($url);
        $this->assertContains($url . ' was not found on this server.', $this->source());
    }

    private function nonMatchingAndDefault($url) {
        $this->withNonMatchingHandler($url);
        $this->withDefaultHandler($url);
    }

    private function withNonMatchingHandler($url) {
        $handlerFile = NULL;
        try {
            $handlerFile = $this->createHandler(self::NAMESPACE_NAME . DIRECTORY_SEPARATOR . self::NAMESPACE_PART2_NAME, self::NAMESPACE_NAME . Classes::NAMESPACE_SEPARATOR . self::NAMESPACE_PART2_NAME, 'NonMatchingName');
            $this->url($url);
            $this->assertEquals('Request Handler Not Found.', $this->title());
        } finally {
            \unlink($handlerFile);
        }
    }

    private function withMatchingHandler($urlNsPart, $urlClassPart) {
        $namespace = \str_replace(DIRECTORY_SEPARATOR, Classes::NAMESPACE_SEPARATOR, $urlNsPart);
        $handlerfile = NULL;
        try {
            $handlerFile = $this->createHandler($urlNsPart, $namespace, $urlClassPart);
            $this->url($urlNsPart . DIRECTORY_SEPARATOR . $urlClassPart);
            $this->assertContains('className: ' . $urlClassPart, $this->source());
            $this->assertContains('namespace: ' . $namespace, $this->source());
            $this->assertContains('filePath: ' . $urlNsPart, $this->source());
        } finally {
            \unlink($handlerFile);
        }
    }

    private function withDefaultHandler($url) {
        try {
            $handlerFile = $this->createHandler(self::NAMESPACE_NAME . DIRECTORY_SEPARATOR .
                    self::NAMESPACE_PART2_NAME, self::NAMESPACE_NAME . Classes::NAMESPACE_SEPARATOR .
                    self::NAMESPACE_PART2_NAME, self::DEF_HANDLER_NAME);
            $this->url($url);
            $this->assertContains('className: ' . self::DEF_HANDLER_NAME, $this->source());
            $this->assertContains('namespace: ' . self::NAMESPACE_NAME .
                    Classes::NAMESPACE_SEPARATOR . self::NAMESPACE_PART2_NAME, $this->source());
        } finally {
            \unlink($handlerFile);
        }
    }

    private function createHandler($filePath, $namespace, $className) {
        if (\strlen($filePath) === 0) {
            $defHandlerFile = self::CLASSPATH_ON_SERVER . $className . ".php";
        } else {
            $defHandlerFile = self::CLASSPATH_ON_SERVER . $filePath . DIRECTORY_SEPARATOR . $className . ".php";
        }

        $nsStatement = NULL;
        if (\strlen($namespace) === 0) {
            $nsStatement = "";
        } else {
            $nsStatement = "namespace $namespace;";
        }

        $defHandlerContent = <<<EOC
<?php
$nsStatement

class $className extends \Id1354fw\View\AbstractRequestHandler {    
    protected function doExecute() {
        echo "in doExecute<br>";
        echo "filePath: $filePath<br>";
        echo "namespace: $namespace<br>";
        echo "className: $className<br>";
    }
}

EOC;
        \file_put_contents($defHandlerFile, $defHandlerContent);
        return $defHandlerFile;
    }

}
