<?php
/**
 * フロントエンドの出力を制御するための基盤を提供します。
 */
class FrontendService {
  var $root;

  function  __construct() {
    ob_start();
  }

  function Start($theme, $template) {
    $this->root = new Frontend($theme, $template);
  }

  function AddError($message) {
    $this->root->AddError($message);
  }

  function AddChild($key, $template) {
    return $this->root->AddChild($key, $template);
  }

  function Complete() {
    $this->root->Process();
    ob_flush();
  }
}


class Frontend {
  var $errors = array();
  private $theme;
  private $includePath;
  private $parent = null;
  private $children = array();

  function __construct($theme, $template, $parent = null) {
    $this->theme = $theme;
    $this->parent = $parent;
    if (isset($theme)) {
      $this->includePath = JINRO_ROOT . "/theme/{$theme}/{$template}.php";
    }
    else {
      $this->includePath = JINRO_ROOT . "/theme/default/{$template}.php";
    }
  }

  function AddChild($key, $template) {
    $child = new Frontend($this->theme, $template, $this);
    $this->children[$key] = $child;
    return $child;
  }

  function AddError($message) {
    $this->errors[] = compact('message');
  }

  function Process() {
    extract($GLOBALS);
    $errors = $this->errors;
    $container = $this->parent;
    include($this->includePath);
  }

  function Insert($name) {
    if (isset($this->children[$name])) {
      $this->children[$name]->Process();
    }
  }
}
