<?php

namespace apexl\Io\services;

use apexl\Io\includes\HookManager;
use apexl\Io\interfaces\GlobalDataInterface;

class GlobalData implements GlobalDataInterface
{
    protected array $data = [];

    public function __construct(
        private readonly HookManager $hookManager
    ) {}

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

    public function addData(string $key, mixed $data, bool $merge = true, bool $getData = false): void
    {
        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;
        }
        if ($getData) {
            //when we add data, we need to load it to store. Initial load should ignore hook calls to prevent infinate loops.
            $this->hookManager->disable();
            $this->getData();
            $this->hookManager->enable();
            //Now that we have default entity data, reload with the hooks.
            $this->getData(null, true);
        }
    }

    public function getData(?string $key = null, bool $reload = false): mixed
    {
        if (!$reload && $key && isset($this->data[$key]) && !empty($this->data[$key])) {
            return $this->data[$key];
        }
        $safeData = $this->data;
        unset($safeData['entities']);
        //allow us to force a reload and return the key
        if ($key) {
            return $this->data[$key] ?? null;
        }

        return $safeData;
    }
}
