<?php
namespace upgrade\services;

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

    public function perform() {       
        $filename = CONFIG_DIR . 'config.php';
        $config = \IoC::resolve( 'config' );
        $eventMediator = \IoC::resolve( 'eventmediator' );
        
        if ( is_writable( $filename ) ) {
            $search = [
                '%default_locale%',
                '%default_timezone%',
                '%base_url%',
                '%database_type%',
                '%database_server%',
                '%database_username%',
                '%database_password%',
                '%database_name%'
            ];
            $replace = [
                'default_locale' => $config['default_locale'],
                'default_timezone' => $config['default_timezone'],
                'base_url' => $config['base_url'],
                'database_type' => $config['database']['type'],
                'database_server' => $config['database']['server'],
                'database_username' => $config['database']['username'],
                'database_password' => $config['database']['password'],
                'database_name' => $config['database']['name']
            ];

            $type = $config['database']['type'];
            
            switch ( $type ) {
            case 'mysql':
                $template = ROOT_DIR . 'upgrade' . DS . TEMPLATES_DIR . 'config_mysql.tpl';
                break;
            case 'pgsql':
                $template = ROOT_DIR . 'upgrade' . DS . TEMPLATES_DIR . 'config_pgsql.tpl';
                $search = array_merge( $search, [
                    '%database_schema%'
                ] );

                $replace = array_merge( $replace, [
                    'database_file' => $config['database']['schema']
                ] );
                break;
            default:
                throw new \LogicException( 'Unknow database' );
            }
            
            file_put_contents( $filename, str_replace( $search, $replace, file_get_contents( $template ) ) );
            $eventMediator->trigger( 'upgrade_succeeded' );
        } else {
            $eventMediator->trigger( 'upgrade_failed', ['The configuration file is not writable.'] );
        }
    }
}
