<?php

namespace apexl\Io\services;

use apexl\ClassEngine\EngineSingleton;

class globalData extends EngineSingleton {

    protected $data;

    public function addData(string $key, $data, $merge = TRUE){
        if($merge) {
            if(isset($this->data[$key]) && is_array($this->data[$key])) {
                $this->data[$key] = array_merge($this->data[$key], $data);
            } else {
                $this->data[$key] = $data;
            }
        } else {
            $this->data[$key] = $data;
        }
    }

    /**
     * Function to allow is to flat replace the data object. Useful if a middleware wants to replace all data in certain situations
     * @param $data
     */
    public function replaceData($data){
        $this->data = $data;
    }

    public function getData(){
        $this->processEntities();
        $safeData = $this->data;
        unset($safeData['entities']);
        return $safeData;
    }

    protected function processEntities(){
        if(!empty($this->data['entities'])) {
            foreach ($this->data['entities'] as $key => $entity){
                $merge = $entity['merge'] ?? TRUE;
                $this->addData($key, (object) $entity['entity']->load($entity['id'])->getData(), $merge);
            }
        }
    }
}