<?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 UninstallPlugin {

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

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

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