<?php

namespace App\Libs\Database\Eloquent;

use App\Models\WebsiteObject;

class ContentTypeCollection extends BaseCollection
{

    public function loadRelated($related, $order = "position", $withPerType = array())
    {
        if (count($this->items) > 0) {
            $ids = array_map(function ($m) {
                return $m->website_object_id;
            }, $this->items);

            $query = WebsiteObject::join("related", "related.related_id", "=", "website_objects.website_object_id")
                ->whereIn("related.website_object_id", $ids)
                ->where("related.type", $related)
                ->selectRaw("website_objects.*, related.website_object_id as related_parent_id");

            if ($order == "position") {
                $query->orderBy("related.position", "asc");
            }

            $results = $query->get();

            $results->load("objectable");

            $this->_loadRelatedRelations($results, $withPerType);

            $dictionary = $this->_buildDictionary($results);

            foreach ($this->items as $model) {
                $key = $model->getAttribute("website_object_id");
                if (isset($dictionary[$key])) {
                    $value = new ContentTypeCollection($dictionary[$key]);

                    if ($order != "position") {
                        $value = $value->sortBy(function ($model) {
                            return $model->title;
                        });
                    }

                    $model->setRelated($related, $value);
                } else {
                    $model->setRelated($related, null);
                }
            }
        }

        return $this;
    }

    protected function _loadRelatedRelations($results, $withPerType)
    {
        if (empty($withPerType)) {
            return;
        }

        foreach ($withPerType as $objectType => $with) {

            load_polymorphic_dependencies($results, "objectable", $objectType, $with, "object_id", "object_type");
        }
    }

    protected function _buildDictionary(WebsiteObjectCollection $results)
    {
        $dictionary = array();

        $foreign = "related_parent_id";

        // First we will create a dictionary of models keyed by the foreign key of the
        // relationship as this will allow us to quickly access all of the related
        // models without having to do nested looping which will be quite slow.
        foreach ($results as $result) {
            $dictionary[$result->{$foreign}][] = $result->objectable;
        }

        return $dictionary;
    }


}
