<?php

namespace Bixo\App\Listeners;

use Illuminate\Support\Facades\Notification;
use Illuminate\Support\Str;
use Bixo\App\Events\AppAction as AppActionEvent;
use Bixo\App\Notifications\AppAction as AppActionNotification;
use Litepie\Actions\Concerns\AsAction;

class AppAction
{
    use AsAction;

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

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

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

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

    /**
     * Check if the event action is allowed.
     *
     * @param   AppActionEvent  $event
     * @return bool
     */
    private function isAllowed(AppActionEvent $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;
    }
}