<?php
namespace apexl\Io\modules\install\services;

use apexl\Io\includes\System;
use apexl\Io\services\Output;
use \apexl\Vault\Vault;

class Install {

    protected $database;

    public function __construct(Vault $database){
        $this->database = $database;
    }

    /**
     * Internal install method.
     * @param $name
     * @param null $vault
     * @return bool
     * @throws \Exception
     */
    public function installModule($name, $vault = null){
        if(!$this->database->isInitialised()){
            //add a message, step out.
            Output::addMessage("db.initialise.fail", 'error', "DB is not initialised.");
        }
        $module = System::$module->getModule($name);
        //if this is set, we're installing it to a specific names database.
        if($vault){
            $this->database->setDefaultVault($vault);
        }

        //get the schema, if there is one.
        if($schema = $module->schema()){
            //loop over the schema and create tables.
            foreach($schema as $table => $config){
                $this->database->createTable($table, $config);
            }
        }

        //Run the install function to allow the installed module to run some arbitrary methods, add data etc
        $module->install();
        //mark the module as installed.
        $module->markInstalled(get_class($module));
        //reload active modules
        System::$module->getAvailableModules();
        return TRUE;
    }
}