<?php

namespace System;

class Config{

    /**
     * Holds the app data
     *
     * @var array
     */
    public static $array = array();

    /**
     * Returns a value from the config array
     * @param  string
     * @return mixed
     */
    public static function get($key){

        $keys = explode('.', $key);

        if (! array_key_exists($file = current($keys), static::$array)) {

            if (is_readable($path = PATH . 'config' . DS . $file . EXT)) {

                static::$array[$file] = require $path;
            }

        }

        return  static::Arr(static::$array, $key);
    }


    /**
     * Return a element from a array
     *
     * @param array
     * @param string
     * @param mixed
     */
    public static function Arr($array, $key){

        // search the array using the dot character to access nested array values
        foreach ($keys = explode('.', $key) as $key) {

           $array = &$array[$key];

        }
        return $array;

    }

    /** 
     * Sets a value in the config array
     * @param string
     * @param mixed
     */
    public static function set($key, $value){

       if(isset(static::$array[$key])) return false;

       return static::$array[$key] = $value;
    }

    /**
     * Removes value in the config array
     * @param string
     */
    public static function erase($key){

        if(!isset(static::$array[$key])) return false;

        unset(static::$array[$key]);
    }


    /**
     * Returns a value from the config array using the
     * method call as the file reference
     *
     * @example Config::app('url');
     *
     * @param string
     * @param array
     */
    public static function __callStatic($method, $arguments)
    {
        $key = $method;

        // key.argument i.e app.url
        if (count($arguments)) {
            
            $key .= '.' . implode('.', $arguments);
        }

        return static::get($key);
    }


}