<?php

namespace Aps\App\Joomla;

require_once __DIR__ . '/bootstrap.php';

/**
 * Simulate com_joomlaupdate component - process native update model
 *
 * administrator/components/com_joomlaupdate/models/default.php
 * \JoomlaupdateControllerUpdate::finalise
 * \JoomlaupdateModelDefault::finaliseUpgrade
 * \JoomlaInstallerScript::update
 */
class Upgrader
{
    public function execute($version, $release)
    {
        jimport('joomla.filesystem.folder');
        if (file_exists(JPATH_INSTALLATION)) {
            \JFolder::delete(JPATH_INSTALLATION);
        }

        // pseudo session a specially for \JoomlaInstallerScript::flushSessions
        \JFactory::$session = new apsSession();

		// \JModelLegacy::addIncludePath(JPATH_ADMINISTRATOR . '/components/com_joomlaupdate/models', 'JoomlaupdateModel');
		//
		// /** @var \JoomlaupdateModelDefault $model */
		// $model = \JModelLegacy::getInstance('default', 'JoomlaupdateModel');
		// \$model->finaliseUpgrade();

        require_once JPATH_ADMINISTRATOR . '/components/com_joomlaupdate/models/default.php';
        $model = new \JoomlaupdateModelDefault;
        $model->finaliseUpgrade();
    }
}

// a specially for \JoomlaInstallerScript::flushSessions
class apsSession
{
    private $apsUser = null;

    /**
     * A specially for uninstall EOS plugin
     *
     * \JoomlaInstallerScript::update
     * \JoomlaInstallerScript::updateDatabase
     * \JoomlaInstallerScript::uninstallEosPlugin
     * \JInstaller::uninstall
     * \JPluginHelper::importPlugin
     * \JPluginHelper::load
     * \JFactory::getUser
     *
     * $instance = self::getSession()->get('user');
     *
     * @param $name
     * @return null
     */
    public function get($name)
    {
        if ('user' !== $name) {
            throw new \Exception('APS upgrade MUST not call session');
        }

        if (!$this->apsUser) {
            // !!! argument MUST NOT be numeric
            $identifier = (string)getenv('SETTINGS_admin_name');
            $this->apsUser = \JUser::getInstance($identifier);
        }
        return $this->apsUser;
    }

    public function getState()
    {
    }

    public function restart()
    {
    }
}
