<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Arr;

use App\Utilities\Paginate;

use App\Traits\ContentElementTrait;
use App\Traits\TagsTrait;
use App\Traits\AppendAttributesTrait;
use App\Traits\PhotosTrait;

use App\Contracts\SearchResultContract;
use App\Utilities\SearchResult;

class LivestreamList extends Model implements SearchResultContract
{
    use HasFactory;
    use ContentElementTrait;
    use TagsTrait;
    use AppendAttributesTrait;
    use PhotosTrait;

    protected $with = ['tags'];

    public function saveContent(array $input, $id = null)
    {
        if ($id >= 1) {
            $livestream_list = LivestreamList::findOrFail($id);
        } else {
            $livestream_list = new LivestreamList();
        }

        $livestream_list->header = Arr::get($input, 'header');
        $livestream_list->show_past = Arr::get($input, 'show_past');
        $livestream_list->show_future = Arr::get($input, 'show_future');
        $livestream_list->save();

        $livestream_list->saveTags($input);

        cache()->tags([cache_name($livestream_list)])->flush();
        return $livestream_list;
    }

    public function getSearchFieldsAttribute()
    {
        return [
            'header',
        ];
    }

    public function getSearchResultTitle($default = null)
    {
        if (mb_strlen($this->header) > 0) {
            return $this->header;
        }
        return $default;
    }

    public function getSearchResultPreview($terms)
    {
        return SearchResult::truncatePreview($this->header, $terms);
    }

    public function getSearchResultRank($terms)
    {
        $rank = 0;
        foreach ($terms as $term) {
            $rank += mb_substr_count($this->header, $term);
        }
        return $rank;
    }
}
