<?php

namespace Snaju\Inception\ORM;

use Doctrine\Common\Collections\Collection;
use Snaju\Inception\Arrays\ArrayFilter;
use Snaju\Inception\Util\ArrayUtil;
use Snaju\Inception\Util\Loaders\Stack;

class DataModelArray
{

    private DataModel $model;

    private int $defaultDepth = 1;

    private int $currentDepth = 0;

    private $array = [];

    private $finalArray = [];

    /**
     * DataModelArray constructor.
     * @param DataModel $model
     * @param array $permit
     * @param array $restrict
     */
    public function __construct(DataModel $model, Stack &$stack = null, int $level = 0)
    {
        $this->model = $model;
        $this->array = $this->loadLevel($model);
    }

    private function loadLevel(DataModel $model): array
    {
        $arr = [];

        foreach ($model->getVars() as $k => $v) {
            if ($v instanceof DataModel) {
                $arr[$k] = "[pointer] pass load to load sub objects";
            } else {
                $arr[$k] = $v;
            }
        }

        return $arr;
    }

    public function load(string ...$paths): DataModelArray
    {
        foreach ($paths as $path) {
            $keys = explode(".", $path);

            $pointer = &$this->model;
            foreach ($keys as $k) {
                if (!isset($pointer->{$k})) {
                    return $this;
                }

                $pointer = &$pointer->{$k};
            }

            ArrayUtil::toArray($this->array, $path, $pointer);
        }
        return $this;
    }

    public function restrict(string ...$paths): DataModelArray
    {
        foreach ($paths as $path) {
            ArrayUtil::unsetKey($this->array, $path);
        }

        return $this;
    }

    public function permit(string ...$paths): DataModelArray
    {
        foreach ($paths as $path) {
            if (!ArrayUtil::pathExist($this->array, $path)) {
                $this->load($path);
            }
        }
        return $this;
    }

    public function get()
    {
        return $this->array;
    }

    public static function build(array $collection, array $display = [], array $hide = [], Stack &$stack = null)
    {
        $a = [];
        foreach ($collection as $item) {
            if ($item instanceof DataModel) {
                $arr = $item->toArray($stack);
                if (count($display) > 0) {
                    $arr->permit($display);
                } else if (count($hide) > 0) {
                    $arr->restrict($hide);
                }

                $a[] = $arr->get();
            }
        }

        return $a;
    }


}

?>