<?php

namespace Tests;

use Illuminate\Database\Eloquent\Factories\Factory;
use Illuminate\Support\Facades\URL;
use Illuminate\Support\Str;

use App\Models\User;
use App\Models\Page;
use App\Models\Version;
use App\Models\ContentElement;

trait ObjectsTrait
{
    public $community = '/community';

    protected function createContentElement(Factory $factory, $page = null, Version $version = null, $state = null)
    {
        if (!$page) {
            $page = Page::factory()->create();
        }

        if ($state) {
            $content_element = ContentElement::factory()->for($factory->{$state}(), 'content')->create();
        } else {
            $content_element = ContentElement::factory()->for($factory, 'content')->create();
        }

        $relationship = Str::plural($page->type);

        $content_element->{$relationship}()->detach();
        $content_element->{$relationship}()->attach($page, [
            'version_id' => $version ? $version->id : $page->draft_version_id,
            'sort_order' => 1,
            'unlisted' => false,
            'expandable' => null,
            'guest' => false,
            'no_margin' => false,
            'filter' => false,
            'hide_print' => false,
            'randomize' => false,
        ]);
        return $content_element;
    }

    protected function getFactory()
    {
        $class_name = $this->getClassString();
        return (new $class_name())::factory();
    }

    protected function getModel()
    {
        $class_name = $this->getClassString();
        return (new $class_name())::factory()->create();
    }

    protected function getClassString()
    {
        return 'App\\Models\\'.Str::studly($this->getClassname());
    }

    protected function getContentableArray($page = null, $array = null)
    {
        if (!$page) {
            $page = Page::factory()->create();
        }

        return collect([
            'contentable_id' => $page->id,
            'contentable_type' => get_class($page),
            'sort_order' => 1,
            'unlisted' => false,
            'expandable' => null,
            'guest' => false,
            'no_margin' => false,
            'filter' => false,
            'hide_print' => false,
            'randomize' => false,
        ])->merge($array ?? []);
    }

    protected function getEditingValue($object, $attribute)
    {
        $current_user = auth()->user();
        $editing = editing();

        auth()->login(User::find(1));
        auth()->user()->enableEditing();

        $object->refresh();

        $value = $object->{$attribute};

        if (!$editing) {
            auth()->user()->disableEditing();
        }

        if ($current_user) {
            auth()->login($current_user);
        } else {
            auth()->logout();
        }

        $object->refresh();

        return $value;
    }
}
