<?php
/*Created by ♞ Raffael Willems */
use Twig\Extension\AbstractExtension;
use Twig\TwigFunction;
class SpotiplayTwigExtension extends AbstractExtension {
  protected $grav;
  protected $data;
  public function __construct($grav) {
    $this->grav = $grav;
    /* $this->data = $this->loadData(); */
  } 
  public function getFunctions() {
    return [ new TwigFunction('spotiplay', [$this, 'spotiplay']), ];
  }
  // Usage from Twig: spotiplay('path.to.key') or spotiplay() for all data 
  public function spotiplay($path = null, $default = null) {
    $this->data = $this->loadData();
    if ($this->data === null) {
      return $default; 
    } 
    if ($path === null) {
      return $this->data;
    } 
    $parts = explode('.', $path);
    $current = $this->data;
    foreach ($parts as $p) {
      if (is_array($current) && array_key_exists($p, $current)) {
        $current = $current[$p];
      } 
      else 
      {
        return $default;
      }
    }
    return $current;
  }
  protected function loadData() {
    $path =  GRAV_ROOT . '/user/data/spotiplay.json';
    if (file_exists($path)) {
      $contents = @file_get_contents($path);
      $arr = json_decode($contents, true);
      if (is_array($arr)) {
        return $arr;
      }
    } 
    return null;
  }
}

