<?php

namespace Bixo\Account\Listeners;

use Illuminate\Support\Facades\Notification;
use Illuminate\Support\Str;
use Bixo\Account\Events\BankAction as BankActionEvent;
use Bixo\Account\Notifications\BankAction as BankActionNotification;
use Litepie\Actions\Concerns\AsAction;

class BankAction
{
    use AsAction;

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

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

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

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

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