<?php

namespace App\Services\Forms\Publications;

use App\Models\Asset;
use App\Models\Objects\FieldType;
use App\Models\Pages\Page;
use App\Models\Publications\Publication;
use App\Models\Publications\PublicationType;
use App\Services\Forms\FormsService;
use App\Transformers\Assets\AssetTransformer;
use App\Transformers\Publications\PublicationTransformer;
use Illuminate\Http\JsonResponse;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Str;
use stringEncode\Encode;

class PublicationVideoForms
    extends FormsService {
    public array $formTitles = ['create' => 'Видео', 'update' => 'Видео'];

    public function form(?string $id = null, array $data = []): array {
        $model = Publication::byUuid($id)->first();
        $groups = [
            ['name' => 'common', 'fields' => $this->commonGroupFields($model)]
        ];
        return ['title' => $this->formTitle($model), 'data' => $groups];
    }

    public function commonGroupFields(?Publication $model): array {

        $params = $model->parsedParams ?? null;

        $fields = [
            [
                'name' => 'published_at',
                'title' => 'Дата публикации',
                'type' => FieldType::DATE,
                'value' => $model->published_at ?? null,
                'required' => true,
            ],
            [
                'name' => 'url',
                'title' => 'Ссылка на видео',
                'type' => FieldType::STRING,
                'required' => true,
                'value' => $params->url ?? null
            ],
            [
                'name' => 'excerpt',
                'title' => 'Описание',
                'type' => FieldType::TEXT,
                'required' => true,
                'value' => $model->excerpt ?? null
            ],
        ];
        return ['data' => $fields];
    }



    public function store(array $data): ?JsonResponse {
        $page = Page::byUuid($data['attach']['page_id'])->first();
        $pub = [];
        $pub['page_id'] = $page->id;
        $pub['excerpt'] = $data['excerpt'];
        $pub['author_id'] = Auth::user()->id;
        $pub['type'] = PublicationType::VIDEO;
        $pub['published_at'] = $data['published_at'];
        if (!empty($data['url'])) {
            $pub['params'] = json_encode([
                'url' => $this->formatUrl($data['url'])
            ]);
        }
        $model = Publication::create($pub, true);
        return fractal($model, new PublicationTransformer())->respond();
    }

    public function update(string $id, array $data): ?JsonResponse {
        $pub = [];
        if (!empty($data['excerpt'])) {
            $pub['excerpt'] = $data['excerpt'];
        }
        if (!empty($data['url'])) {
            $pub['params'] = json_encode([
                'url' => $this->formatUrl($data['url'])
            ]);
        }
        $pub['published_at'] = $data['published_at'];
        $model = Publication::byUuid($id)->firstOrFail();
        $model->update($pub);
        return fractal($model->fresh(), new PublicationTransformer())->respond();
    }

    public function formatUrl($url): string {
        $videoIdYoutube = '';
        $videoIdRutube = '';
        $videoUrl = '';
        switch (true) {
            case str_contains($url, $mask = 'https://youtu.be/'):
            case str_contains($url, $mask = 'https://www.youtube.com/watch?v='):
                $videoIdYoutube = str_replace($mask, '', $url);
                break;
            case str_contains($url, $mask = 'https://rutube.ru/video/'):
                $videoIdRutube = str_replace($mask, '', $url);
                break;
            default:
                $videoUrl = $url;
                break;
        }
        if ($videoIdYoutube != '') {
            $videoUrl = "https://www.youtube.com/embed/$videoIdYoutube";
        }
        if ($videoIdRutube != '') {
            $videoUrl = "https://rutube.ru/play/embed/$videoIdRutube";
        }
        return $videoUrl;
    }
}
