<?php
namespace services\plugin;
/**
 * @author Jérôme Brilland
 * @version 3.0
 * @copyright (c) 2019-2021, Jérôme Brilland
 * @license http://www.gnu.org/licenses/gpl.txt GNU General Public License
 */
class InstallPlugin {

    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 . 'install.php';

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

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