<?php

namespace Realestate\Video\Listeners;

use Illuminate\Support\Facades\Notification;
use Illuminate\Support\Str;
use Realestate\Video\Events\VideoAction as VideoActionEvent;
use Realestate\Video\Notifications\VideoAction as VideoActionNotification;
use Litepie\Actions\Concerns\AsAction;

class VideoAction
{
    use AsAction;

    private $allowedActions = [
        'before' => [],
        'after' => ['create'],
    ];

    /**
     * Handle the VideoActionEvent.
     *
     * @param   VideoActionEvent  $event
     * @return mixed
     */
    public function handle(VideoActionEvent $event)
    {
        $function = Str::camel($event->action);
        return $this->$function($event);
    }

    /**
     * Create a new $video.
     *
     * @param   VideoActionEvent  $event
     * @return void
     */
    public function create(VideoActionEvent $event)
    {
        $client = $event->video->client;
        Notification::send($client, new VideoActionNotification($event));
    }

    /**
     * Handle the VideoActionEvent as a listener.
     *
     * @param   VideoActionEvent  $event
     * @return mixed
     */
    public function asListener(VideoActionEvent $event)
    {
        if ($this->isAllowed($event)) {
            return $this->handle($event);
        }
    }

    /**
     * Check if the event action is allowed.
     *
     * @param   VideoActionEvent  $event
     * @return bool
     */
    private function isAllowed(VideoActionEvent $event)
    {
        if ($event->when == 'before' &&
            !in_array($event->action, $this->allowedActions['before'])) {
            return false;
        }

        if (($event->when == 'after' &&
            !in_array($event->action, $this->allowedActions['after']))
        ) {
            return false;
        }

        return true;
    }
}