<?php

namespace Tests\Unit;

use Tests\TestCase;

use Illuminate\Foundation\Testing\WithFaker;
use Illuminate\Support\Arr;
use Illuminate\Support\Str;

use App\Models\TextBlock;
use App\Models\ContentElement;
use App\Models\Page;

use Tests\Unit\PageLinkTestTrait;
use Tests\Unit\ContentElementRenderTestTrait;

class TextBlockTest extends TestCase
{
    use PageLinkTestTrait;
    use ContentElementRenderTestTrait;
    use WithFaker;

    protected function getModel()
    {
        return $this->createContentElement(TextBlock::factory())->content;
    }

    protected function getLinkFields()
    {
        return [
            'body',
            'side_text',
        ];
    }

    public function test_a_text_block_can_be_created()
    {
        $input = TextBlock::factory()->raw();

        $text_block = (new TextBlock())->saveContent($input, null);

        $this->assertInstanceOf(TextBlock::class, $text_block);
        $this->assertEquals(Arr::get($input, 'header'), $text_block->header);
        $this->assertEquals(Arr::get($input, 'body'), $text_block->body);
    }

    public function test_a_text_block_has_a_content_element()
    {
        $text_block = $this->createContentElement(TextBlock::factory())->content;
        $this->assertInstanceOf(ContentElement::class, $text_block->contentElement);
    }

    public function test_a_text_block_can_return_a_search_result()
    {
        $page = Page::factory()->create();

        $header = $this->faker->sentence;
        $term = Str::random(12);

        $text_block = $this->createContentElement(TextBlock::factory([
            'header' => $header,
            'body' => '<p>'.$this->faker->paragraph.' '.$term.'</p>',
        ]), $page)->content;

        $this->assertNotNull($text_block->getSearchResultTitle('foobar'));
        $this->assertNotEquals($text_block->getSearchResultTitle('foobar'), 'foobar');

        $this->assertNotNull($text_block->getSearchResultPreview([$term]));
    }

    public function test_the_default_search_result_title_is_returned_if_there_is_no_header()
    {
        $page = Page::factory()->create();

        $text_block = $this->createContentElement(TextBlock::factory([
            'header' => null,
        ]), $page)->content;

        $this->assertNotNull($text_block->getSearchResultTitle('foobar'));
        $this->assertEquals($text_block->getSearchResultTitle('foobar'), 'foobar');
    }
}
