<?php
namespace App\Traits;

trait NodeTrait
{

    /**
     * Return an key-value array indicating the node's depth with $seperator
     *
     * @param $column
     * @param null $key
     * @param string $seperator
     * @param string $nb
     * @param boolean $showDescription
     * @return Array
     */
    public static function getNestedList($column, $key = null, $seperator = ' ', $nb = '├ ', $showDescription = false)
    {
        $instance = new static();
        $key = $key ?: $instance->getKeyName();
        $depthColumn = $instance->getDepthColumnName();

        if ($showDescription) {
            if ($instance instanceof \App\Models\Nav) {
                $nodes = $instance::with('description')->where('content_model', '=', '')->orWhereNull('content_model')->get()->toHierarchy()->toArray();
            } else {
                $nodes = $instance::with('description')->get()->toHierarchy()->toArray();
            }

            foreach ($nodes as &$node) {
                $node[$column] = $node['description'][$column];
                unset($node['description']);
            }
        } else {
            if ($instance instanceof \App\Models\Nav) {
                $nodes = $instance::where('content_model', '=', '')->orWhereNull('content_model')->get()->toHierarchy()->toArray();
            } else {
                $nodes = $instance::get()->toHierarchy()->toArray();
            }
        }

        if (!$nodes) {
            return [];
        }

        $nodes = $instance->toVerticality($nodes);
        
        return array_combine(array_map(function ($node) use ($key) {
            return $node[$key];
        }, $nodes), array_map(function ($node) use ($seperator, $depthColumn, $column, $nb) {
            return $node[$depthColumn] > 0 ? str_repeat($seperator, $node[$depthColumn]) . $nb . $node[$column] : $node[$column];
        }, $nodes));
    }

    private static function toVerticality($nodes)
    {
        static $tmp;
        foreach ($nodes as &$node) {
            
            $childs = $node['children'];
            
            if ($childs) {
                array_forget($node, 'children');
                $tmp[] = $node;
                self::toVerticality($childs);
            } else {
                $tmp[] = $node;
            }
        }
        return $tmp;
    }


}