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

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

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

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