<?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
*/

/**
 * Render the children of this node at some place else in the view tree.
 * Their position remains the same for the variables that they acceess.
 * Only the timing of rendering is impacted.
 *
 * Capture to can only work if the thing to capture is "above" the insertion point
 * in the tree or has trigger an out of order rendering using buffering.
 *
 * If the destination has already been rendered, the children of this view
 * Will not be rendered.
 */
class Wact_View_ShiftTo extends Wact_View_Partial {

    const APPEND = 1;
    const REPLACE = 2;
    const PREPEND = 3;

    /**
     * 
     */
    protected $mode = self::APPEND;

    /**
     * Target view to place output
     * @var string
     */
    protected $targetViewId;
    
    /**
    * Construct this object.
    */
    public function __construct($targetViewId, $mode = self::APPEND) {
        parent::__construct();
        $this->targetViewId = $targetViewId;
        $this->mode = $mode;
    }

    /**
     * Trigger rendering
     * @return void
     */
    public function delayedRender() {
        parent::render();
    }

    /**
     * Shift the output of the child views and place it somewhere else in the tree
     */
    public function render() {
    
        if (isset($this->preRenderListeners)) {
            $this->preRenderListeners->notify($this);
        }

        $target = $this->root->findChild($this->targetViewId);

        if ($target && $target->canChangeChildren()) {
            $callback = new Wact_View_Callback(array($this, 'delayedRender'));
            switch ($this->mode) {
            case self::APPEND:
                $target->appendChild($callback);
                break;
            case self::PREPEND:
                $target->prependChild($callback);
                break;
            case self::REPLACE:
                $target->removeAllChildren();
                $target->appendChild($callback);
                break;
            }
        }
    }

}

?>