<?php

namespace Bixo\CrossTrade\Listeners;

use Illuminate\Support\Facades\Notification;
use Illuminate\Support\Str;
use Bixo\CrossTrade\Events\OfferUsVehicleAction as OfferUsVehicleActionEvent;
use Bixo\CrossTrade\Notifications\OfferUsVehicleAction as OfferUsVehicleActionNotification;
use Litepie\Actions\Concerns\AsAction;

class OfferUsVehicleAction
{
    use AsAction;

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

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

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

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

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