<?php
namespace services\plugin;

use \models\Plugin;

/**
 * @author Jérôme Brilland
 * @version 2.0
 * @copyright (c) 2021, Jérôme Brilland
 * @license http://www.gnu.org/licenses/gpl.txt GNU General Public License
 */
class UpgradePlugin {

    protected $pluginName;

    public function __construct( $pluginName ) {
        $this->pluginName = $pluginName;
    }

    public function perform( $listener ) {
        $pluginName = explode( '[', $this->pluginName )[0];
        $filename = APP_DIR . 'plugins' . DS . $pluginName . DS . 'plugin.json';
        $plugin = Plugin::fromJSON( \JSONHandler::decode( file_get_contents( $filename ), true ) );
        if ( !$plugin ) {
            $listener->upgradePluginFailed( $pluginName );
        }
        
        $filename = APP_DIR . 'plugins' . DS . $pluginName . DS . 'upgrade.php';

        $configurationHandler = \IoC::resolve( 'databaseConfigurationHandler' );
        $settings = new \Configuration( $configurationHandler );
        $plugins = unserialize( $settings['plugins'] );
        if ( !array_key_exists( $this->pluginName, $plugins ) ) {
            $listener->upgradePluginFailed( $pluginName );
        }

        if ( ( !file_exists( $filename ) ) || ( !include( $filename ) ) ) {
            $listener->upgradePluginFailed( $pluginName ); 
        } else {
            unset( $plugins[$this->pluginName] );
            $plugins[$plugin->fullname] = 0;
            $settings['plugins'] = serialize( $plugins );
            $configurationHandler->save();
            $listener->upgradePluginSucceeded( $pluginName );
        }
    }
}
