<?php
namespace models;

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

    public $fullname;
    public $name;
    public $version;
    public $url;
    public $description;
    public $installedVersion;
    public $isInstalled;
    public $isActive;
    public $hasNewerVersion;
    public $settingsPage;

    public static function fromJSON( $json ) {
        $plugin = new Self();
        $plugin->fullname = $json['name'] . '[' . $json['version'] . ']';
        $plugin->name = $json['name'];
        $plugin->version = $json['version'];
        $plugin->url = $json['url'];
        $plugin->description = $json['description'] ?? null;
        $plugin->settingsPage = $json['settings_page'] ?? null;
        $plugin->isInstalled = false;
        $plugin->isActive = false;
        $plugin->installedVersion = null;
        $plugin->hasNewerVersion = false;
        return $plugin;
    }

    /**
     * @access public
     */
    public static function findAll() {
        $plugins = self::findInstalledPlugins();
        foreach ( scandir( APP_DIR . 'plugins' ) as $pluginName ) {
            $filename = APP_DIR . 'plugins' . DS . $pluginName . DS . 'plugin.json';
            if ( file_exists( $filename ) && !array_key_exists( $pluginName, $plugins ) ) {
                $plugin = Plugin::fromJSON( \JSONHandler::decode( file_get_contents( $filename ), true ) );
                if ( $plugin ) {
                    $plugins[$pluginName] = $plugin;
                }
            }
        }
        return $plugins;
    }

    public static function findInstalledPlugins() {
        $settings = \IoC::resolve( 'settings' );
        $installedPlugins = unserialize( $settings['plugins'] );
        $plugins = [];
        foreach( $installedPlugins as $fullname => $isActive ) {
            list( $pluginName, $version ) = explode( '[', $fullname );
            $version = str_replace( ']', '', $version );
            $filename = APP_DIR . 'plugins' . DS . $pluginName . DS . 'plugin.json';
            if ( !is_readable( $filename ) ) {
                throw new \RuntimeException( sprintf( 'The file %s does not exist or is not readable.', $filename ) );
            }
            $plugin = Self::fromJSON( \JSONHandler::decode( file_get_contents( $filename ), true ) );
            if ( $plugin ) {
                $plugin->fullname = $plugin->name . '[' . $version . ']';
                $plugin->isInstalled = true;
                $plugin->isActive = $isActive;
                $plugin->installedVersion = $version;
                $plugin->hasNewerVersion = version_compare($plugin->version, $version, '>' );
                $plugins[$pluginName] = $plugin;
            }
        }
        return $plugins;
    }

}
