<?php if ( ! defined( 'ABSPATH' ) ) { die; } // Cannot access pages directly.

class omfw_SVG {

	private static $instance = null;

	protected $symbols = array();
	protected $hookRegistered = false;

	public function __construct() {
	}

	public static function getInstance() {
		if ( self::$instance == null ) {
			self::$instance = new omfw_SVG();
		}

		return self::$instance;
	}

	public function register( $symbols ) {
		$this->symbols = array_merge( $this->symbols, $symbols );
	}

	public function get( $key ) {
		$svg = false;
		if ( isset( $this->symbols[ $key ] ) ) {
			$svg = '<svg><use xlink:href="#' . esc_attr( $key ) . '"></use></svg>';
			$this->symbols[ $key ]['output'] = true;

			$this->registerHook();
		}

		return $svg;
	}

	public function e( $key ) {
		echo $this->get( $key );
	}

	protected function registerHook() {
		if ( $this->hookRegistered ) {
			return;
		} else {
			add_action( 'wp_footer', array( $this, 'outputContainer' ) );
			$this->hookRegistered = true;
		}
	}

	public function outputContainer() {
		$symbols = array();
		foreach ( $this->symbols as $key => $symbol ) {
			if ( isset( $symbol['output'] ) && $symbol['output'] ) {
				$symbols[] = '<symbol id="' . esc_attr( $key ) . '" viewBox="' . esc_attr( $symbol['viewBox'] ) . '">' . $symbol['code'] . '</symbol>';
			}
		}
		if ( ! empty( $symbols ) ) {
			echo '<svg version="1.1" xmlns="http://www.w3.org/2000/svg" style="display:none">' . implode( '', $symbols ) . '</svg>';
		}
	}
}