<?php
/**
* Web Application Component Toolkit
*
* @link http://www.phpwact.org/
*
* @author Wact Development Team
* @link http://www.phpwact.org/team
*
* @copyright Copyright 2006, Jeff Moore
* @license http://opensource.org/licenses/mit-license.php MIT
*/

/*
Eventually to replace WactCliEnvironment.
*/

/**
* Represents a development project for WACT development tools.
*/
class Wact_Tool_Project {

    public $projectFile;
    public $localProjectFile;
    protected $config;
    protected $sections;
    
    /**
    * Load a project from a specific directory.
    */
    static function Load($directory) {
        $dir = $directory;
        $file = NULL;
        while ((substr_count($dir, DIRECTORY_SEPARATOR) > 1) && file_exists($dir) && is_dir($dir) && is_readable($dir)) {
            $file = $dir . '/.wactproj';
            if (file_exists($file)) {
                break;
            }
            $dir = dirname($dir);
        }

        if (!$file) {
            throw new Exception("Cannot locate project for $directory.");
        }
        
        return new self($file);
    }
    
    /**
    * Construct a new project instance for a given project file.
    */
    function __construct($file) {
        if (!file_exists($file)) {
            throw new Exception ("Project file $file Does not Exist");
        }
        $this->projectFile = $file;

        $localFile = dirname($file) . '/.wactproj.local';
        if (file_exists($localFile) && is_readable($localFile)) {
            $this->localProjectFile = $localFile;
        }
    }

    /**
    *   Load Configuration settings from project files
    */
    protected function LoadProjectFiles() {
        $configvalues = NULL;

        $this->config = parse_ini_file($this->projectfile);
        // check for parse_ini_errors
        
        if (empty($this->localProjectFile)) {
            return;
        }
    
        $local = parse_ini_file($this->localProjectFile, TRUE);
        // Double Check result

        foreach ($local as $section => $options ) {
            if ( !array_key_exists($section, $this->config) ) {
                $this->config[$section] = $options;
            } else {
                foreach ($options as $opt => $value ) {
                    $this->config[$section][$opt] = $value;
                }
            }
        }
    }

    function __get($name) {
        if (isset($this->sections[$name])) {
            return $this->sections[$name];
        } else {
            throw new Exception("Section $name does not exist.");
        }
    }
    
    function __set($name, $section) {
        $this->sections[$name] = $section;
        $section->bindTo($this, $this->config[$name]);
    }

    function __isset($name) {
        return array_key_exists($name, $this->properties);
    }
    
    function __unset($name) {
        throw new Exception('Cannot unregister sections.');
    }

}
  
?>