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

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

class UpdateMusicAction implements ToFeedAction
{

    public $musicFeed;

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

    public function __invoke(MusicData $musicData)
    {

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

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

        if($musicData->is_loaded_preview){
            if($existPreview = $this->musicFeed->getMedia('preview')->first()){
                $existPreview->delete();
            }
            $this->musicFeed->addMedia($musicData->preview)->toMediaCollection('preview');
        }

        if($musicData->is_loaded_music){
            $result_time_common = $this->calcTimeFile($musicData->times);

            foreach ($musicData->musics as $music) {
                $name = $music->getClientOriginalName();
                $time = @$result_time_common[$name];
                $this->musicFeed->addMedia($music)
                    ->withCustomProperties(['time' => $time])
                    ->toMediaCollection('common');
            }
        }


        if($musicData->is_loaded_paid_music){
            $result_time_paids = $this->calcTimeFile($musicData->times_paid);

            foreach ($musicData->musics_paid as $music) {
                $name = $music->getClientOriginalName();
                $time = @$result_time_paids[$name];
                $this->musicFeed->addMedia($music)
                    ->withCustomProperties(['time' => $time])
                    ->toMediaCollection('paid');
            }
        }

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

        DB::commit();

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

    protected function calcTimeFile($time_musics)
    {
        $times = array_map(function($line){
            $line = explode(',', $line);
            return [$line[0] => $line[1]];
        }, $time_musics);
        return  array_merge(...$times);
    }
}
