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

use DB;
use App\Domain\Feeds\Models\Feed;
use App\Domain\Feeds\ToFeedAction;
use App\Domain\Musics\DataTransferObjects\MusicData;

class CreateMusicAction implements ToFeedAction
{
    public function __invoke(MusicData $musicData)
    {
        DB::beginTransaction();

        if(empty($musicData->title)){
            $file_count = count($musicData->musics);
            $first_file = $musicData->musics[0]->getClientOriginalName();
            $filename = pathinfo($first_file, PATHINFO_FILENAME);
            $musicData->title = $filename . ' (' . $file_count . ')';
        }

        $musicFeed = Feed::create([
            'title' => $musicData->title,
            'body' => $musicData->body,
            'price' => $musicData->price,
            'is_paid' => $musicData->is_paid,
            'user_id' => $musicData->user->id,
            'is_ads' => false,
            'type' => 'musics',
        ]);

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

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

        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];
                $musicFeed->addMedia($music)
                    ->withCustomProperties(['time' => $time])
                    ->toMediaCollection('paid');
            }
        }

        DB::commit();

        return $musicFeed;
    }

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