<?php

class LanguageRepository extends ModelRepository
{
  private static $_singletonInstance = null;

  public function __construct()
  {
    parent::__construct('Language');
  }


  /**
   * Returns an initiated LanguageRepository
   *
   * @return LanguageRepository
   */
  public static function getInstance()
  {
    if (self::$_singletonInstance === null)
    {
        self::$_singletonInstance = new LanguageRepository();
    }

    return self::$_singletonInstance;
  }


  /**
   * Cache all languages in APC
   *
   * @param  int $id
   */
  public function cacheAll()
  {
    // Attempt to pull the config from the memory cache
    if (apcu_enabled())
    {
      $pdo = PDOMysqlConnection::getInstance();
      $stmt = $pdo->prepareAndExec('SELECT * FROM language ORDER BY phrase_key ASC');

      $language = [];
      $language['en-us'] = [];
      while ($record = $stmt->fetch(PDO::FETCH_NUM))
      {
        $language[$record[1]][$record[0]] =
        [
          's' => $record[2],
          'p' => $record[3]
        ];
      }

      apcu_store('language', $language);
      return true;
    }

    return false;
  }


  /**
   * Get all languages
   *
   * @param  int $id
   */
  public function getAll()
  {
    // Attempt to pull the config from the memory cache
    if (apcu_enabled() && apcu_exists('language'))
    {
      $language = apcu_fetch('language');
    }
    else
    {
      $pdo = PDOMysqlConnection::getInstance();
      $stmt = $pdo->prepareAndExec('SELECT * FROM language ORDER BY phrase_key ASC');


      $language = [];
      $language['en-us'] = [];
      while ($record = $stmt->fetch(PDO::FETCH_NUM))
      {
        $language[$record[1]][$record[0]] =
        [
          's' => $record[2],
          'p' => $record[3]
        ];
      }

      // Store the config in the cache
      if (apcu_enabled())
      {
        apcu_store('language', $language);
      }
    }

    return $language;
  }

}
