<?php
/**
 *
 * @author jason.xie@victheme.com
 *
 */
class VTCore_Zeus_Layout_Factory
  extends VTCore_Bootstrap_Grid_BsContainerFluid {

  private $areas;
  private $regions;


  public function buildElement() {

    // Overloading object with areas and region configurations
    $this->areas = new VTCore_Zeus_Layout_Areas();
    $this->regions = new VTCore_Zeus_Layout_Regions();


    // Building the areas
    foreach ($this->areas->getAreas() as $name => $context) {
      $object = new VTCore_Wordpress_Layout_Area($context);
      $object->setMachineID('area-' . $name);
      $this->addChildren($object);
    }


    // Sorting areas by context weight
    $areas = $this->getChildrens();
    usort($areas, array($this, 'sortByWeight'));
    $this->setChildren($areas);


    // Building the Regions and inject to its parent areas
    foreach ($this->regions->getRegions() as $name => $context) {
      $object = new VTCore_Wordpress_Layout_Region($context);
      $object->addContext('regionId', $name);
      $object->setMachineID('region-' . $name);

      $parents = $this->findChildren('id', 'area-' . $object->getContext('parent'));

      foreach ($parents as $parent) {
        $parent->addChildren($object);
      }
    }


    // Sorting regions by context weight
    foreach ($this->getChildrens() as $areas) {
      $regions = $areas->getChildrens();
      usort($regions, array($this, 'sortByWeight'));
      $areas->setChildren($regions);
    }

  }

  private function sortByWeight($a, $b) {
    return $a->getContext('weight') > $b->getContext('weight') ? 1 : -1;
  }

  public function getAreas() {
    return $this->areas->getAreas();
  }

  public function getRegions() {
    return $this->regions->getRegions();
  }

}