<?php

namespace Hecate\Components;

use Hecate\Lodash;

//Rename to ComponentMods
class ComponentMods {
	private static $instance;
	private $cachedData  = array();
	private $defaultData = array();
	private $insertedInDbDefaults;

	private function __construct() {
		$this->loadData();

		//the first time the page is published
        add_action( 'after_switch_theme', array( $this, 'insertDefaultDataToDatabase' ) );
	}

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

		return self::$instance;
	}

	public function insertDefaultDataToDatabase() {
		if ( !!get_theme_mod( 'insertedInDbDefaults', false )) {
			return;
		}
		$themeModsToInsert   = array();

		if ( ! is_array( $this->defaultData ) ) {
			return;
		}
		foreach ( $this->defaultData as $componentId => $data ) {

			$settings = array();
			foreach ( $data as $settingId => $property ) {
				$path              = strtr(
					':componentId.:settingId',
					array(
						':componentId' => $componentId,
						':settingId'   => $settingId,
					)
				);
				$settings[ $path ] = $property;
			}

			$themeModsToInsert = array_merge( $themeModsToInsert, $settings );
		}


		foreach ( $themeModsToInsert as $key => $mod ) {
			set_theme_mod( $key, $mod );
		}
		set_theme_mod( 'insertedInDbDefaults', true );
	}

	public static function init() {
		return self::getInstance();
	}

	public static function getData( $path, $defaultValue = null ) {
		$instance = static::getInstance();
		$value    = Lodash::get( $instance->cachedData, $path, null );
		if ( $value !== null ) {
			return $value;
		}

		if ( $instance->insertedInDbDefaults ) {
			$instance->cachedData[ $path ] = get_theme_mod( $path, $defaultValue );
		} else {
			$instance->cachedData[ $path ] = Lodash::get( $instance->defaultData, $path, $defaultValue );
		}
		return $instance->cachedData[ $path ];
	}

	public static function getChildrenIds( $componentId ) {
		$childrenPath = strtr( ':componentId.children', array( ':componentId' => $componentId ) );
		return static::getData( $childrenPath, array() );
	}

	public static function getComponentName( $componentId ) {
		$componentPath = sprintf( '%s.component', $componentId );
		return static::getData( $componentPath );
	}

	private function loadThemeDefaultData() {
        // phpcs:ignore WPThemeReview.CoreFunctionality.FileInclude.FileIncludeFound
		$defaultData       = require get_template_directory() . '/inc/theme-defaults.php';
		$this->defaultData = $defaultData;
	}


	public function loadData() {
		$this->insertedInDbDefaults = get_theme_mod( 'insertedInDbDefaults', false );
		if ( ! $this->insertedInDbDefaults ) {
			$this->loadThemeDefaultData();
		}
	}
}
