<?php
namespace App\Domain\Videos\Action;

use App\Domain\Feeds\Models\Feed;
use DB;
use App\Domain\Feeds\ToFeedAction;
use App\Domain\Videos\DataTransferObjects\VideoData;

class CreateVideoAction implements ToFeedAction
{
    public function __invoke(VideoData $videoData)
    {
        DB::beginTransaction();

        //$youtube_code = $videoData->youtube ? $this->getCodeYoutube($videoData->youtube) : '';

        $videoFeed = Feed::create([
            'title' => $videoData->title,
            'body' => $videoData->body,
            'price' => $videoData->price,
            'is_paid' => $videoData->is_paid,
            'user_id' => $videoData->user->id,
            'type' => 'videos',
            'is_ads' => false,
            //'iframe_code' => $youtube_code,
        ]);

        foreach ($videoData->videos as $video) {
            $videoFeed->addMedia($video)->toMediaCollection('common');
        }
        if($videoData->is_loaded_preview){
            $videoFeed->addMedia($videoData->preview)->toMediaCollection('preview');
        }
        if($videoData->is_loaded_videos_paid){
            foreach ($videoData->videos_paid as $video) {
                $videoFeed->addMedia($video)->toMediaCollection('paid');
            }
        }


        DB::commit();

        return $videoFeed;
    }

    private function getCodeYoutube($video)
    {
        $youtuberegexp = '/(?:youtube\.com\/(?:[^\/]+\/.+\/|(?:v|e(?:mbed)?)\/|.*[?&]v=)|youtu\.be\/)([^"&?\/\s]{11})/i';
        preg_match($youtuberegexp, $video, $matches);
        return @$matches[1];
    }
}
