<?php
namespace install\services;

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

    private $databaseSettings;
    private $settings;

    public function __construct( array $databaseSettings, array $settings ) {
        $this->databaseSettings = $databaseSettings;
        $this->settings = $settings;
    }

    public function perform( $listener ) {
        $i18n = \IoC::resolve( 'i18n' );
        
        $filename = CONFIG_DIR . 'config.php';
        
        if ( is_writable( $filename ) ) {
            $search = [
                '%default_locale%',
                '%default_timezone%',
                '%base_url%',
                '%database_type%',
                '%database_server%',
                '%database_username%',
                '%database_password%',
                '%database_name%'
            ];
            $replace = [
                'default_locale' => \IoC::resolve( 'locale' ),
                'default_timezone' => 'Europe/Paris',
                'base_url' => $this->settings['base_url'],
                'database_type' => $this->databaseSettings['type'],
                'database_server' => $this->databaseSettings['server'],
                'database_username' => $this->databaseSettings['username'],
                'database_password' => $this->databaseSettings['password'],
                'database_name' => $this->databaseSettings['name']
            ];

            $type = $this->databaseSettings['type'];
            
            switch ( $type ) {
            case 'mysql':
                $template = ROOT_DIR . 'install' . DS . TEMPLATES_DIR . 'config_mysql.tpl';
                break;
            case 'pgsql':
                $template = ROOT_DIR . 'install' . DS . TEMPLATES_DIR . 'config_pgsql.tpl';
                $search = array_merge( $search, [
                    '%database_schema%'
                ] );

                $replace = array_merge( $replace, [
                    'database_file' => $this->databaseSettings['schema']
                ] );
                break;
            default:
                throw new \LogicException( 'Unknow database' );
            }
            
            file_put_contents( $filename, str_replace( $search, $replace, file_get_contents( $template ) ) );
            $listener->installSucceeded();
        } else {
            $listener->installFailed( $i18n->__( 'config_file_could_not_be_written' ) );
        }
    }
}
