<?php

declare(strict_types=1);

namespace Crossroads\Magento\Test\Integration;

use Mage;
use Zend_Controller_Request_Abstract;

Use PHPUnit\Framework\TestCase as BaseCase;

class TestCase extends BaseCase {
    public function getPreserveSession(): bool {
        return true;
    }

    public function setUp(): void {
        MagentoManager::setUp();

        if( ! $this->getPreserveSession()) {
            $_SESSION = [];
        }

        // TODO: After test to ensure log files are empty
    }

    public function tearDown(): void {
        MagentoManager::logQueries();
    }

    public function onNotSuccessfulTest($e): void {
        MagentoManager::logQueries();

        throw $e;
    }

    public function getSystemLog(): string {
        return MagentoManager::readLogFile("system.log");
    }

    public function getExceptionLog(): string {
        return MagentoManager::readLogFile("exception.log");
    }

    public function initMagento() {
        MagentoManager::init();
    }

    public static function runRequest(Zend_Controller_Request_Abstract $request) {
        return MagentoManager::runRequest($request);
    }

    public static function loginCustomer(integer $customerId) {
        $sess     = Mage::getSingleton("customer/session");
        $customer = Mage::getModel("customer/customer")
            ->setWebsiteId(Mage::app()->getStore()->getWebsiteId())
            ->load($customerId);
        $sess->setCustomerAsLoggedIn($customer);
    }

    public static function createController($module, $controller) {
        $fileName  = Mage::getModuleDir("controllers", $module) . DS . uc_words($controller, DS) . "Controller.php";
        $className = $module . "_" . uc_words($controller)."Controller";
        $app       = Mage::app();
        $request   = $app->getRequest();
        $response  = $app->getResponse();

        require_once $fileName;

        return Mage::getControllerInstance($className, $request, $response);
    }
}
