<?php

namespace Saswp;

class Shortcode
{
  public $id = false;
  public $name = false;
  public $attributes = [];

  public function __construct()
  {
    $this->init();
  }

  public function content($attrs)
  {
    return 'Empty :)';
  }

  public function footer()
  {
	 echo "\n<!-- " . esc_html($this->id) . " element -->\n";
  }

  public function jsonProp($name, $default=false)
  {
    $return = $default;

    if (isset($this->attributes[ $name ])) {
      $return = $this->attributes[ $name ]['default'];
    }
    return wp_json_encode($return);
  }

  public function attributes($attrs = [])
  {
    if ('object' == gettype($attrs)) {
      return $attrs;
    }

    $default = array_map(function($attr) {
      return $attr['default'];
    }, $this->attributes);

    $attrs = array_merge($default, $attrs);

    return new class ($attrs) {
      public function __construct($attrs=[]) {
        foreach($attrs as $key => $value) {
          $this->{$key} = $value;
        }
      }

      public function toHtml() {
        $attrs = [];
        foreach(get_object_vars($this) as $key => $value) {
          if (!$value) continue;
          if (is_array($value)) $value = wp_json_encode($value);
          $attrs[ $key ] = "{$key}='{$value}'";
        }
        return join(' ', $attrs);
      }
    };
  }

  public function render($attrs=[])
  {
    ob_start();
    $this->content($this->attributes($attrs));
    return ob_get_clean();
  }

  static $shortcodes = [];

  // Register new self instance
  static function register($instance)
  {
    self::$shortcodes[ $instance->id ] = $instance;
  }

  // Run shortcode, works like do_shortcode method but with data
  // \Saswp\Shortcode2::run('sas-example', ['message' => 'Hello']);
  // Same as: do_shortcode('[sas-example message="Hello"]');
  static function run($id, $attrs=[])
  {
    if ($instance = self::get($id)) {
      return $instance->render($attrs);
    }
  }

  static function get($id)
  {
    return self::$shortcodes[ $id ] ?? false;
  }

  // List all shortcodes
  static function all()
  {
    return array_values(self::$shortcodes);
  }

  // Initialize
  public function init()
  {
    $this->attributes = array_merge([
      'id' => ['default' => '', 'description' => 'Element ID'],
      'class' => ['default' => '', 'description' => 'Element classes'],
    ], $this->attributes);

    $this->attributes = array_map(function($attr) {
      return array_merge([
        'description' => '',
        'default' => '',
      ], $attr);
    }, $this->attributes);

    $instance = $this;
    add_shortcode($this->id, function($attrs) use($instance) {
      $attrs = is_array($attrs)? $attrs: [];
      $attrs = $this->attributes($attrs);
      return $instance->render($attrs);
    });

    foreach(['wp_footer', 'admin_footer'] as $action) {
      add_action($action, [ $this, 'footer' ]);
    }
  }
}
