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

use DB;
use App\Domain\Feeds\Models\Feed;
use App\Domain\Feeds\ToFeedAction;
use App\Domain\Feeds\Enums\StatusEnum;
use App\Domain\Videos\DataTransferObjects\VideoData;
use Spatie\MediaLibrary\MediaCollections\Models\Media;

class UpdateVideoAction implements ToFeedAction
{

    public $videoFeed;

    public function __construct(Feed $videoFeed)
    {
        $this->videoFeed = $videoFeed;
    }

    public function __invoke(VideoData $videoData)
    {

        $status = $this->videoFeed->status;
        if($status === StatusEnum::BANNED()){
            $status = StatusEnum::EDITABLE();
        }
        if($status === StatusEnum::APPROVED()){
            $status = StatusEnum::EDITABLE();
        }

        DB::beginTransaction();
        $this->videoFeed->fill([
            'title' => $videoData->title,
            'body' => $videoData->body,
            'price' => $videoData->price,
            'is_paid' => $videoData->is_paid,
            'status' => $status,
            'is_ads' => false,
        ])->save();

        if($videoData->is_loaded_video){
            foreach ($videoData->videos as $video) {
                $this->videoFeed->addMedia($video)->toMediaCollection('common');
            }
        }

        if($videoData->is_loaded_preview){
            if($existPreview = $this->videoFeed->getMedia('preview')->first()){
                $existPreview->delete();
            }
            $this->videoFeed->addMedia($videoData->preview)->toMediaCollection('preview');
        }
        if($videoData->is_loaded_videos_paid){
            foreach ($videoData->videos_paid as $video) {
                $this->videoFeed->addMedia($video)->toMediaCollection('paid');
            }
        }

        if(count($videoData->removedItems)){
            foreach ($videoData->removedItems as $removedItem) {
                if($media = Media::find($removedItem)){
                    $media->delete();
                }
            }
        }

        DB::commit();

        return $this->videoFeed->refresh();
    }


}
