<?php
/**
 * funkce pouzivane pri konfiguraci Dependency Injectin
 */
namespace IZON\Admin\DI;

use \Exception;

use \IZON\Admin\Config;

use DI\Definition\EntryReference;

use IZON\Admin\DI\Definition\Helper\ModuleConfigDefinitionHelper;
use IZON\Admin\DI\Definition\Helper\ModuleConfigsDefinitionHelper;


if (! function_exists('IZON\Admin\DI\moduleConfig')) {
    
    /**
     * nacita informace z nastaveni modulu v db
     * @param string $moduleConfigName  nazev konfigurace co se ma vytahnout z konfigurace modulu
     * @return ModuleConfigDefinitionHelper
     */
    function moduleConfig($moduleConfigName, $moduleIdentifier = NULL) {
        // TODO: je celkem ochcavka, udelat lip
        if( $moduleIdentifier == NULL ) {
            $moduleIdentifier = Config::$moduleIdentifier;
        }
        return new ModuleConfigDefinitionHelper($moduleIdentifier, 
                                              $moduleConfigName);
    }
}

if (! function_exists('IZON\Admin\DI\moduleConfigs')) {
    
    /**
     * vsechna nastaveni pro modul
     * @return ModuleConfigsDefinitionHelper
     */
    function moduleConfigs($moduleIdentifier = NULL) {
        // TODO: je celkem ochcavka, udelat lip
        if( $moduleIdentifier == NULL ) {
            $moduleIdentifier = Config::$moduleIdentifier;
        }
        return new ModuleConfigsDefinitionHelper($moduleIdentifier);
    }
}


if (! function_exists('IZON\Admin\DI\moduleGet')) {
    /**
     * Provede načtení hodnoty z modulu
     * podobné jako IZON\DI\get
     * 
     * @param string $entryName nazev polozky co se ma vytahnout
     * @param string $moduleIdentifier indentifier modulu, z kereho se maji data vytahnout
     *
     * @return EntryReference
     */
    function moduleGet($entryName, 
                        $moduleIdentifier = NULL) {
        $completeEntryName = Config::getModuleEntryName($entryName, 
                                                $moduleIdentifier);
        return \IZON\DI\get($completeEntryName);
    }
}

if (! function_exists('IZON\Admin\DI\moduleIdentifier')) {
    /**
     * vrati identifier z nejakeho modulu
     * podobné jako IZON\DI\get
     * 
     * @param string $entryName nazev polozky co se ma vytahnout
     * @param string $moduleIdentifier indentifier modulu, z kereho se maji data vytahnout
     *
     * @return EntryReference
     */
    function moduleIdentifier($entryName, 
                        $moduleIdentifier = NULL) {
        $completeEntryName = Config::getModuleEntryName($entryName, 
                                                $moduleIdentifier);
        return $completeEntryName;
    }
}

if (! function_exists('IZON\Admin\DI\modulesDirs')) {
    /**
     * returns directories of all installed modules
     */
    function modulesDirs() {
        return \IZON\DI\get(Config::MODULES_DIRS_IDENTIFIER);
    }
}

if (! function_exists('IZON\Admin\DI\daoInit')) {
    /**
     * 
     * @param array $configArray konfigurace, ktera se pouzije
     * @param string $dbConnectionId pod jekym id je ulozeno db pripojeni
     * @param array|string $daoClasses tridy interface, ktere se maji inicializovat
     * @return array konfiguracni pole s pridanymi dai
     */
    function daoInit($configArray,
                       $dbConnectionId, 
                       $daoClasses) {
        foreach($daoClasses as $daoClass) {
            $configArray[$daoClass] = \IZON\DI\factoryBean(\IZON\DB\DaoFactoryBean::class)
                                            ->constructor(\IZON\DI\get($dbConnectionId), $daoClass);
        }
        return $configArray;
    }
}

if (! function_exists('IZON\Admin\DI\daoModuleInit')) {
    /**
     * Inicializace dai pro modul
     * 
     * @param array $configArray
     * @param string $baseDir - jakeho adresare se budou daa nacitat
     * @param string $namespace namespace bez prvniho \
     * @param string $dbConnectionId
     * @param array $externalDaoClasses - pokud chceme nacitat enajaka externi daa
     * @return array
     */
    function daoModuleInit($configArray, $baseDir, $namespace, $dbConnectionId, $externalDaoClasses = array()) {
      if(!empty($externalDaoClasses) && is_array($externalDaoClasses)) {
        foreach($externalDaoClasses as $daoClass) {
          $configArray[$daoClass] = \IZON\DI\factoryBean(\IZON\DB\DaoFactoryBean::class)
                                          ->constructor(\IZON\DI\get($dbConnectionId), $daoClass);
        }
      }
      $path = $baseDir.'src/Dao';
      foreach(scandir($path) as $file) {
        if(in_array($file, array('.', '..'))) continue;
        $daoClass = $namespace.pathinfo($file, PATHINFO_FILENAME);
        $configArray[$daoClass] = \IZON\DI\factoryBean(\IZON\DB\DaoFactoryBean::class)
                                          ->constructor(\IZON\DI\get($dbConnectionId), $daoClass);
      }
       
      return $configArray;
    }
}

if (! function_exists('IZON\Admin\DI\useModuleInit')) {
    /**
     * Nasype potrebna daa, servisy a controlerry do module-config.php
     * 
     * @param string $baseDir zakladni adresar 
     * @param string $namespace 
     * @param array $dirs pole s adresari, pro ktere chceme generovat "use"
     */
    function useModuleInit($baseDir, $namespace, $dirs) {
      $buff = [];
      $fileContent = file_get_contents($baseDir.'module-config.php');
      if(!empty($dirs) && is_array($dirs)) {
        foreach ($dirs as $key => $dir) {
          $path = $baseDir.'src/'. str_replace("\\", "/", $dir);

          foreach(scandir($path) as $file) {
            if(pathinfo($file, PATHINFO_EXTENSION) != 'php') continue;//  in_array($file, array('.', '..'))
            $buff[] = 'use '.$namespace.$dir.'\\'.  pathinfo($file, PATHINFO_FILENAME).';';
          }
          $buff[] = "\r\n";
        }
      }
      
      $startSign  = '// --- START USE SECTION ---';
      $endSign    = '// --- END USE SECTION ---';
      $startSection = strpos($fileContent, $startSign);
      if($startSection !== FALSE) {
        $endSection = strpos($fileContent, $endSign);
        if($endSection !== FALSE) {
          $before = substr($fileContent, 0, $startSection + strlen($startSign));
          $after  = substr($fileContent, $endSection);
          $fileContent = $before."\r\n".implode("\r\n", $buff)."\r\n".$after;
          //echo $fileContent;
          //die;
          \IZON\File\saveToFile($baseDir.'module-config.php', $fileContent);
        }
      }
    }
}

