<?php

namespace Bixo\Account\Listeners;

use Illuminate\Support\Facades\Notification;
use Illuminate\Support\Str;
use Bixo\Account\Events\PayrecAction as PayrecActionEvent;
use Bixo\Account\Notifications\PayrecAction as PayrecActionNotification;
use Litepie\Actions\Concerns\AsAction;

class PayrecAction
{
    use AsAction;

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

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

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

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

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