<?php

/**
 * Class ArrayHandlerController
 * 
 * Responsável por controlar e gerenciar os ArrayHandler.
 */
class ArrayHandlerController {
  private static $handlers = array();

  public static function have_rows($key, $id = null) {

    if (empty(self::$handlers)) {
      $value = get_post_meta($id, $key, true);

      if ($value && !Helper::is_array_of_arrays($value))
        $value = array($value);

      if (!empty($value)) {
        self::$handlers[$key] = new ArrayHandler($key, $value);
        return true;
      } else {
        return false;
      }
    }

    if (isset(self::$handlers[$key])) {
      $handler = self::$handlers[$key];
      if ($handler->have_rows()) {
        return true;
      } else {
        unset(self::$handlers[$key]);
        return false;
      }
    } else {
      $handler_end = end(self::$handlers);
      $value_end = $handler_end->get_field($key);
      if (!empty($value_end)) {

        if (!Helper::is_array_of_arrays($value_end))
          $value_end = array($value_end);

        if (!empty($value_end)) {
          self::$handlers[$key] = new ArrayHandler($key, $value_end);
          return true;
        } else {
          return false;
        }
      } else {
        return false;
      }
    }
  }

  public static function the_row() {
    $handler_end = end(self::$handlers);
    $handler_end->the_row();
  }

  public static function get_field($key) {
    $handler_end = end(self::$handlers);
    return $handler_end->get_field($key);
  }

  public static function get_index() {
    $handler_end = end(self::$handlers);
    return $handler_end->get_index();
  }

  public static function in_loop() {
    return count(self::$handlers) > 0;
  }
}
